Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a prop to {children} in React? [duplicate]

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>); 
like image 816
Joe C Avatar asked Nov 07 '20 21:11

Joe C


People also ask

How do you pass a prop to a child in React?

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.

How do you pass a prop in React?

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.

How do you pass props from one child component to another?

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!


1 Answers

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>
);
like image 107
Fullstack Guy Avatar answered Oct 05 '22 23:10

Fullstack Guy