In React, you can pass a component as a prop to another component by treating it like any other prop. Here is an example:
function ParentComponent(props) { return ( <div> <h1>Parent Component</h1> <ChildComponent childProp={props.childComponent}/> </div> ); } function ChildComponent(props) { return ( <div> <h2>Child Component</h2> {props.childProp} </div> ); } function App() { return ( <div> <ParentComponent childComponent={<h3>Hello from child component</h3>}/> </div> ); }
In the example above, we have a ParentComponent
that takes a prop called childComponent
. This prop is passed to ChildComponent
, which renders it in the component. In the App
component, we pass a JSX element as a prop to the ParentComponent
. This JSX element is then rendered in the ChildComponent
.
You can also pass a component by using its name directly instead of wrapping it in JSX. For example:
function App() { return ( <div> <ParentComponent childComponent={ChildComponent}/> </div> ); }
In this case, we pass the ChildComponent
directly to ParentComponent
, and ParentComponent
renders it as a child component.