Skip to content
This repository has been archived by the owner on Jul 2, 2024. It is now read-only.

Accessing ref of consumers #13

Open
quybeans opened this issue Aug 30, 2019 · 0 comments
Open

Accessing ref of consumers #13

quybeans opened this issue Aug 30, 2019 · 0 comments
Assignees

Comments

@quybeans
Copy link

quybeans commented Aug 30, 2019

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:

w

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.

@quybeans quybeans changed the title Passing reference passing reference Aug 30, 2019
@thien-do thien-do changed the title passing reference Accessing ref of consumers Sep 21, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant