How to pass the props to the children inside the React Component

Sometime we have to pass the props to a child component inside the parent component (Wraper component). But how to?

Make a example below to know.

Create the parent component:

import React from "react";

function ParentComponent({ children }) {
  const childrenRender = Object.assign({}, children);
  childrenRender.props = {
    ...children.props,
    title: "This is children prop title content"
  };
  return <div className="ParentComponent">{childrenRender}</div>;
}

export default ParentComponent;


Copy this code


In the codes above, the props of the children component is readonly, that why we have to create a new children called childrenRender with all of old children's props and we add the title prop in new children component.

When reuse the wraper component with a child component:


import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import ParentComponent from "./ParentComponent";

function App() {
  const Children = ({ title }) => <div className="Children">{title}</div>;
  return (
    <div className="App">
      <ParentComponent>
        <Children />
      </ParentComponent>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Copy this code


© 2019 4codev

Created with love by Sil.