Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  59] [ 4]  / answers: 1 / hits: 5900  / 2 Years ago, wed, july 27, 2022, 12:00:00

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

More From » reactjs

 Answers
1

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


[#50] Monday, July 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zane

Total Points: 471
Total Questions: 94
Total Answers: 91

Location: Bahrain
Member since Sun, Mar 27, 2022
2 Years ago
zane questions
Tue, Sep 15, 20, 00:00, 4 Years ago
Fri, Jul 31, 20, 00:00, 4 Years ago
Fri, Jun 26, 20, 00:00, 4 Years ago
;