'In React is passing a component directly to another component allowed?
I am new to react and was wondering if you are allowed to directly pass one or more components to another instead of passing it as a prop or child.
Consider the following:
const ChildComponent = () => {
return (
<h1> I am a child </h1>
);
}
const ChildComponent2 = () => {
return (
<h1> I am also a child </h1>
);
}
//Passing directly to Parent
const ParentComponent = () => {
return (
<div>
<ChildComponent/>
<ChildComponent2/>
</div>
);
}
//Passing as children
const ParentComponent2 = ({ChildComponent, ChildComponent2}) => {
return (
<div>
{ChildComponent}
{ChildComponent2}
</div>
);
}
<ParentComponent>
<ChildComponent/>
<ChildComponent2/>
</ParentComponent>
I have read about passing components as children vs props. I have also seen that it is an antipattern to create functional components inside of functional components. I can't seem to find anything about directly passing one or more components inside of another without using props or children. When testing it out, the component rendered properly, but I am not sure if it's a valid way of passing components to a parent component.
Solution 1:[1]
With React's composition model, you can take advantage of the special children prop to pass children elements directly.
// With props object destructuring
const ParentComponent = ({children}) => {
return (
<div>
{children}
</div>
);
}
// Without props object destructuring
const ParentComponent = (props) => {
return (
<div>
{props.children}
</div>
);
}
This lets you pass other components as children to the parent component by nesting the JSX:
// A pair of children components
const ChildComponent1 = () => {
return <div>I am child 1</div>;
};
const ChildComponent2 = () => {
return <div>I am child 2</div>;
};
// Compose your parent component with its children
const App = (props) => {
return (
<ParentComponent>
<ChildComponent1 />
<ChildComponent2 />
</ParentComponent>
);
}
As per the React docs, this is the recommended way of composing your components.
As a final thought, sometimes you might need specialized components or partials and perhaps not make use of children but always render a specific component.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HereBeAndre |
