0

I have a simple scenario: A parent class component and a child stateless component, and I would like to invoke the function defined in the child component directly from the parent. The solution that I came across here looks like this:

const { forwardRef, useRef, useImperativeHandle } = React;

// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {

  // The component instance will be extended
  // with whatever you return from the callback passed
  // as the second argument
  useImperativeHandle(ref, () => ({

    getAlert() {
      alert("getAlert from Child");
    }

  }));

  return <h1>Hi</h1>;
});

const Parent = () => {
  // In order to gain access to the child component instance,
  // you need to assign it to a `ref`, so we call `useRef()` to get one
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click</button>
    </div>
  );
};

ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);

but the issue here is that I have those components defined in different files, and I don't know how can I get ahold of useRef if I declare it in the child component, and it doesn't really look readable anyway. Can you guys help me out with this, or provide another approach ? Thanks.

Zed
  • 5,683
  • 11
  • 49
  • 81
  • This has been answered already in the `SO` post you linked. If you have components in different files then just use the `import` statement whenever you need it. As for the not-readable part, as the answer in the `SO` post suggests, " this is generally not the way to go about things in React land" so yeah it'll feel weird. What is that you're doing that you need this exact functionality? – goto Feb 09 '20 at 12:01
  • Basically the child component renders a table with the list of messages. Now I am passing the messages directly from the parent component as props, but the child component takes care of the tables's pagination data, such as the current page variable. So when the messages in the table change, I want to reset the page to the first one as well. I'm not sure that it makes sense to hold those pagination variables in the parent component and pass them to the child like I do with messages.. – Zed Feb 09 '20 at 12:12
  • It absolutely does and should be done this way instead. Why not just create a `Table` component that does the render + the business logic for pagination? Then pass whatever data you get from an API to `Table` from `App` (for example). What you're trying to do above is definitely a "hack," so I'd stay away from it. – goto Feb 09 '20 at 12:15

0 Answers0