I have a Parent component that acts as a wrapper to its children. How do I pass a prop to a child that will be rendered using the format below?
import React, { useEffect, useState } from 'react';
const Parent = ({ children }) => {
const [completeState, setCompleteState] = useState(false);
useEffect(
() => {
/* .. code that runs then sets completeState to true */
setCompleteState(true);
}, []
);
return (
<section>
/*
how to pass a 'didComplete' prop to children?
didComplete={completeState}
*/
{children} // Child component below would be rendered here with the didComplete prop passed in
</section>
)
}
import React from 'react';
const Child = ({ didComplete }) => (<h1>The function completed? {didComplete}</h1>);
Passing Props to Children in React To display them, you need to include props. children or this. props. children (for class components) in your return statement.
export default App; Basically that's how props are passed from component to component in React. As you may have noticed, props are only passed from top to bottom in React application's component hierarchy. There is no way to pass props up to a parent component from a child component.
Just call an alert method in the childToParent function and pass that function as a prop to the child component. And in the child component, accept the childToParent function as a prop. Then assign it to an onClick event on a button. That's it!
The props.children
is a React Element, which is nothing but a plain JS object having the description of what needs to be rendered in the DOM.
To provide additional details, we need to clone the existing React Element object and provide the additional details.
To do this we can use the React.cloneElement
API to pass the additional prop to the children
:
return (
<section>
{React.cloneElement(children, {didComplete: completeState})}
</section>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With