Categories
React Answers

How to pass React component as props?

Spread the love

Sometimes, we want to pass React component as props.

In this article, we’ll look at how to pass React component as props.

How to pass React component as props?

To pass React component as props, we can put the components between the parent component’s tags and then then access them in the parent component with the children prop.

For instance, we write

const Label = (props) => <span>{props.children}</span>;
const Tab = (props) => <div>{props.children}</div>;
const Page = () => (
  <Tab>
    <Label>Foo</Label>
  </Tab>
);

to add the Label and Tab components that take the children prop.

Then we define the Page component that renders the Label component in the Tab component.

As a result, a div with a span inside it with the Foo text should be rendered since the children component are replaced by the component between the opening and closing tags.

Conclusion

To pass React component as props, we can put the components between the parent component’s tags and then then access them in the parent component with the children prop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *