25

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>); 
kind user
  • 40,029
  • 7
  • 67
  • 77
Joe C
  • 1,685
  • 2
  • 16
  • 26

1 Answers1

36

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>
);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44