0

I am working with the concepts of ReactJS and stumbled upon this very interesting case,

I have a button in my parent component, which when clicked will access a simple string defined in child component.

I understand to pass data from parent to child we use, and to a child to parent we have to use callback functions, But I am not sure how do I use callback function in this scenario. I have played around a little with defining function etc but nothing seems to really work.

My Main.js file

import React from "react";
import Child from "./Child";

function handleClick(props) {
  console.log("clicked");
}

function Main(props) {
  return (
    <div>
      <button onClick={handleClick}>click</button>
      {console.log(props)}
    </div>
  );
}

export default Main;

My Child.js component

import React from "react";

function statement() {
  return "A sentence";
}

function Child(props) {
  //   let sentence = "This is from the child component";
  return (
    <div>
      <p>The child says {props.name} </p>
    </div>
  );
}

export default Child;

Thank you for reading, sorry if it sounds too basic. Any help would be much appreciated.

anshul
  • 661
  • 9
  • 27
  • Does this answer your question? [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) Refer to this answer for that question - https://stackoverflow.com/a/45582558/9867745 Since you are using a FC, you need to replace componentDidMount in that answer with useEffect hook in your case – Karthikeyan Jan 28 '20 at 21:12

1 Answers1

0

you can create a ref in parent component and pass it to child component and then access the child state through that ref like:

function Main(props) {
  const child = useRef()
  const handleClick = () => {
    // get child state
    child.current.getState()
  }
  return <Child innerRef={child} />
}

function Child({ innerRef }) {
  const [someState, setSomeState] = useState()
  useImperativeRef(innerRef, () => ({ getState: () => someState }), [someState])

  return <SomeComponent />
}

You can read more about above code in official docs.

Muhammad Ali
  • 2,538
  • 2
  • 16
  • 21
  • This does seem like a great approach, but I really want to use callback functions, not ref, context API etc – anshul Jan 28 '20 at 20:35
  • Then you’ll have to keep the child state in main component. – Muhammad Ali Jan 28 '20 at 20:42
  • Please refer to this link [link](http://[link](https://towardsdatascience.com/passing-data-between-react-components-parent-children-siblings-a64f89e24ecf) Here it is stated we can do that using props and callback function – anshul Jan 28 '20 at 20:51