-
Notifications
You must be signed in to change notification settings - Fork 38
Parent Child Independence
Can you use the component inside any type of parent element, or with any type of child elements?
Unless there is a direct need, it's usually best to design a component such that it can work inside any type of parent element and (if the component has a <slot>
to accept children) with any type of child element. This lets users of your component find uses for it in situations beyond those you have imagined.
It’s fine for a component to treat certain types of children specially (e.g., a <select>
treats <optgroup>
children differently than <option>
children), but if a component treats all its children in the same general way, it’s preferable if children can be of any element type.
For example, you may imagine that your photo slideshow component will only ever need to handle <img>
child elements, but someone may want to use it show a slideshow of other types of elements, including custom elements that behave like <img>
elements. Unless there is a compelling need to restrict the set of children to a specific type of element, you are probably best off handling child elements of all types.
// Limiting
const imagesToHandle = this.querySelectorAll('img');
// Better
const childrenToHandle = this.children;
To allow for the presence of Auxiliary Content, you can query for all children, then filter out those that you don't want to handle. That is, rather than only handling a certain type of element, exclude those you can't handle.
The same principle applies when writing a component that you expect to only be used inside a particular type of a parent. Other users of your component may find applications for it inside other types of parent elements. Consider what the component should do if found inside a plain parent element such as a <div>
. For comparison, even a <li>
found outside its normal <ul>
or <ol>
context will still render as a list item.
At a minimum, a component that finds itself inside an unexpected host type should avoid throwing exceptions. Keep in mind that components can be subclassed, so even a compatible host could have an unexpected tag. (See Subclassable.) Rather than directly expecting a parent or child element to be of a particular class, consider using duck typing to see whether the parent/child supports the interface members you require.