Sometimes, we want to pass optional elements to a component as a prop in React.
In this article, we’ll look at how to pass optional elements to a component as a prop in React.
How to pass optional elements to a component as a prop in React?
To pass optional elements to a component as a prop in React, we can create a component that accepts the children
prop.
For instance, we write:
import React, { useState } from "react";
const Panel = ({ children }) => {
return <div>{children}</div>;
};
const Title = ({ children }) => {
return <h1>{children}</h1>;
};
export default function App() {
return (
<Panel>
<Title>hello world</Title>
</Panel>
);
}
We defined the Panel
and Title
components that take the children
prop.
children
can take one or more React components or strings.
We set 'hello world'
as the value of Title
‘s children
prop.
And we set Title
as the value of Panel
‘s children
prop.
So we see ‘hello world’ displayed in big text.
Conclusion
To pass optional elements to a component as a prop in React, we can create a component that accepts the children
prop.