Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass Data from Parent To Child Component in ReactJs

In App.Js file I’m passing "This data is coming from Parent" to Child.Js
But here I want to pass this on button through onClick not dataParentToChild={data}. Just Like Child.Js file working in onClick={handleChildToProp}
enter the link description here
App.Js

function App(props) {
    // Child To Parent
    const [word, setWord] = useState("");
    const handleChildToParent = (words) => setWord(words);

    // Parent To Child
    const data = "This data is coming from Parent";

    return (
        <>
            <h1>"Parent Data"</h1>
            <h2>{word}</h2>
            <Child
                // Without button Working Fine
                dataParentToChild={data}
                // With button Working Fine
                dataChildToParent={handleChildToParent}
            />
        </>
    );
}

Child.Js

const Child = (props) => {
    // Parent To Child
    const handleChildToProp = () => {
        props.dataChildToParent("This data is comming from Child");
    };

    return (
        <>
            <h1>Child Components</h1>
            <h2>{props.dataParentToChild}</h2>
            <button onClick={handleChildToProp}>Data Child To Parent</button>
        </>
    );
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to make the button onClick update a state to trigger a re-render of dataParenToChild, like so:

function App(props) {
  // Child To Parent
  const [word, setWord] = useState('');
  const [parentToChild, setParentToChild] = useState('');
  const handleChildToParent = (words) => setWord(words);

  // Parent To Child
  const handleParentToChild = () => {
    setParentToChild('This data is coming from Parent');
  };

  return (
    <>
      <h1>"Parent Data"</h1>
      <h2>{word}</h2>
      <button onClick={handleParentToChild}>Data Parent To Child</button>
      <Child
        // Without button Working Fine
        dataParentToChild={parentToChild}
        // With button Working Fine
        dataChildToParent={handleChildToParent}
      />
    </>
  );
}

Working solution

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading