Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React refs when parent and child are function components

I have two React components, Parent and Child. Both must be function components. I am trying to change the state of Child from Parent. I believe the best way to do this is using refs, but I haven't been able to get it to work.

I've tried creating a ref in Parent and passing it down to child, but this causes an error. I considered forwardRef() but I'm not sure that will work either.

const Parent = () => {
  const ref = React.useRef();

  const closeChild = () => {
    ref.current.setOpen(false);
  };

  return (
    <div>
      <Child ref={ref} onClick={closeChild} />
    </div>
  );
};
const Child = () => {
  const [open, setOpen] = useState(false);

  return (
    <div>
      {open ? <p>open</p> : <p>closed</p>}
    </div>
  );
};

The code as it is now produces this error message:

react-dom.development.js:506 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?`

like image 339
tomasina Avatar asked Jan 01 '23 17:01

tomasina


1 Answers

Only stateful React components can expose the ref automatically. If using functional component, I think you'll need to use forwardRef for the child component: e.g.

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
like image 108
jsdeveloper Avatar answered Jan 08 '23 00:01

jsdeveloper