javascriptreactjsreact-propspass-data

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>
        </>
    );
};

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