0

I am trying to do: Change child state as in this tutorial: Change child state from parent

Tutorial uses class component, I've tried to use function components.It gives an error like "Function components don't have instances so they can't have refs" So I used forwardRef (for the first time) according to a stackoverflow answer here

Code:

    import React,{useRef,forwardRef, useEffect} from "react";

const Component = (props) => {
function sayHello(){
  console.log("hello")
}

return <h1>{props.children}</h1>
}
const ForwardComponent = forwardRef((props,ref)=> (<Component ref={ref}> {props.children} </Component>))


export default function App() {
  const hello = useRef()
  useEffect(()=>{
    hello.current.sayHello()
  })
  return (
    <div>
      <ForwardComponent ref={hello}>Hello</ForwardComponent>
    </div>
  );
}

note: I could use context api or redux here, but I believe it should be simpler in my use case. Also I get to learn something new

Ali Mert Çakar
  • 290
  • 1
  • 8
  • 15
  • Though it may be new, using refs for imperative behavior like this should be avoided when possible. Read [this](https://reactjs.org/docs/refs-and-the-dom.html#when-to-use-refs) about refs and their alternatives. (If you insist, you're looking for `useImperativeHandle`) – joshwilsonvu Jun 26 '20 at 20:12
  • Check this answer to know how to use `ImperativeHandle` as @JoshWilson suggests https://stackoverflow.com/questions/37949981/call-child-method-from-parent – ludwiguer Jun 26 '20 at 20:21
  • Thank you very much. I overlooked that little method – Ali Mert Çakar Jun 26 '20 at 23:10

0 Answers0