0

I'm trying to implement wrapper tags that binds to events on child DOM element and then does something according to them.

I have following code:


const Wrapper: React.FC = (props) => {
    // How do I get access to child div DOM element here??
    someComponent.eventListenerOn(childDOMElement);

    return <>{props.children}</>;
};

const ChildStuff: React.FC = () => {
    return (
        <Wrapper>
            <div id="xyzzy"></div>
        </Wrapper>
    );
};

In Wrapper, how do I get access to child DOM element?

jtiai
  • 611
  • 5
  • 11

2 Answers2

0

You can do that with React ref, try to check here How do I access refs of a child component in the parent component

And React document about ref: Refs and the DOM

ThanhPhanLe
  • 1,315
  • 3
  • 14
  • 25
0

You can use ref to access any DOM element. However, you'll need to wait until react writes its changes to DOM and then you can access it using useEffect hook. Here's how you do it using hooks:

const Wrapper = (props) => {
    const ref = React.useRef(null);

    React.useEffect(() => {
      if (ref.current) {
        // ref.current has the DOM element. Do what you want.
      }
    })

    return <div ref={ref}>{props.children}</div>;
};

const ChildStuff = () => {
  return (
    <Wrapper>
      <div id="xyzzy"></div>
    </Wrapper>
  );
};
ron4ex
  • 1,073
  • 10
  • 21
  • 1
    In functional component, useRef should be used instead of createRef – NCM Jul 26 '19 at 06:46
  • Nice catch. Updated it. For anyone wondering why, read more about [createRef vs useRef](https://stackoverflow.com/questions/54620698/whats-the-difference-between-useref-and-createref) – ron4ex Jul 26 '19 at 07:37