Home >Web Front-end >JS Tutorial >How to Pass Props from Child to Parent in React.js?
Passing Props to Parent Component in React.js
Can't we send a child's props to its parent using events in React.js?
While other solutions exist, they often overlook a fundamental point. Parents already possess the props they pass to their children. So, there's no need for children to send those props back to parents.
Better Approach
Child:
The child component is kept simple.
const Child = ({ text, onClick }) => ( <button onClick={onClick}>{text}</button> );
Parent (Single Child):
Utilizing the prop it sends to the child, the parent handles the click event.
const Parent = ({ childText }) => { const handleClick = (event) => { // Parent already has the child prop. alert(`Child button text: ${childText}`); alert(`Child HTML: ${event.target.outerHTML}`); }; return <Child text={childText} onClick={handleClick} />; };
Parent (List of Children):
The parent manages multiple children without losing access to necessary information.
const Parent = ({ childrenData }) => { const handleClick = (childData, event) => { alert( `Child button data: ${childData.childText} - ${childData.childNumber}` ); alert(`Child HTML: ${event.target.outerHTML}`); }; return ( <div> {childrenData.map((childData, index) => ( <Child key={index} text={childData.childText} onClick={e => handleClick(childData, e)} /> ))} </div> ); };
This strategy respects encapsulation and reduces coupling by avoiding reliance on the child's internal structure.
The above is the detailed content of How to Pass Props from Child to Parent in React.js?. For more information, please follow other related articles on the PHP Chinese website!