festival
festival copied to clipboard
Accessing ref of consumers
Some components need to have a reference to a DOM element created by their consumers. For example, a Popover
component needs to know its target
's DOM element's position to render the content next to it:
We are going to consider 3 approaches:
1. Ref is handled by the consumers
<Popover content={<Content />}>
{(ref) => (
<Button ref={ref}>Click me</Button>
)}
</Popover>
Result:
<button>Click me</button>
Pros:
- Declarative.
- Maintain the DOM order.
Cons:
- Not so much convenience.
- Target component must handle a ref props.
2. Wrap target with an element ex: span
and then ref to that span
element
<Popover content={<Content />}>
<Button ref={ref}>Click me</Button>
</Popover>
Result:
<span>
<button>Click me</button>
</span>
Pros:
- Convenience
Cons:
- DOM order is not changed. Might lead to unexpected results.
3. Find a the DOM that created from target's React Component
<Popover content={<Content />}>
<Button ref={ref}>Click me</Button>
</Popover>
<button>Click me</button>
Pros:
- Convenience.
- DOM structure is not changed.
Cons:
- Target element must be ref-able (a valid DOM).
How: Using ReactDOM.findElement().
Thought
On the Popover
case, I think Solution #3
is should fit the most, since it maintain the DOM order also the convenience for library user.