/  Technology   /   Children Prop in React
 Children Prop in React

 Children Prop in React

 

What are children?

In React we have a main component which is referenced as the parent component and the other sub components which are inherited from the parent component are regarded as child or children components.

The children, in React, refer to the generic box whose contents are unknown until they are passed from the parent components.

In Simple words it means that the component will display whatever is included in between the opening and closing tags while invoking the component. The components would usually be invoked from App components. A parent component scan pass whatever is needed in the child components, even generated layout features that can then be rendered by the child.

{ props.children }: Implementation is pretty simple. In the parent components, import the child components, but instead of invoking it with a self-closing tag, use an standard open and/or closing tag. The information that you want to pass through props(properties) — in addition to the standard implementations of passing props(properties) — is placed between the opening and closing tags of the child components.

Example of Parent Component 

import React from ".react";
import ChildComponent from "./ChildComponent";
const ParentComponent = () => {
  return (
    <div style={{ backgroundColour: "blue", padding: "10px", width: "50vw" }}>
      <h3>This is a ParentComponent</h3>
      <ChildComponent>
        <p style={{ backgroundColour: "white", padding: "10px" }}>
          This paragraph will show up in the child, but we sent from the parent
        </p>
      </ChildComponent>
    </div>
  );
};
export default ParentComponent;

Implementing <ParentComponent />: The <ParentComponent /> defines a paragraph that will be passed down to the <ChildComponent /> as props.

Example of Child Component :

import React from ".react";
const ChildComponent = (props) => {
  return (
    <div style={{ backgroundColor: "grey", padding: "10px" }}>
      <h4>This is a Child Component</h4>
      {props.children}
    </div>
  );
};
export default ChildComponent;

Implementing <ChildComponent />: In the ChildComponent. { props.children } will render any data that has been passed down from the parent, allowing the ParentComponent to customize the contents of the ChildComponent.

Output:

Here in the output we can see that the result of content being passed to a child from the parent component, that is then rendered in the child.

 Children Prop in React

 

Leave a comment