In React, we can use props in a deeply nested component without passing them through its ancestors by utilizing Component Composition.
It is the concept that enables us to use component libraries like Material UI, Chakra UI, and React Bootstrap to compose and create custom interfaces for our apps without having to edit those component libraries to pass our props
If you want to avoid passing props down to a monolithic component with deep levels of nested children components like so:
root.render(<FirstBox />)
function FirstBox() {
let data = "Hello world!";
return <SecondBox data={data} />
}
function SecondBox(props) {
return <ThirdBox data={props.data} />
}
function ThirdBox(props) {
return <p>Data: {props.data}</p>
}
// just imagine if we needed to pass down a lot of props!
Use Component Composition to define props at the top level of your component and use it in other components without passing it through like so:
root.render(<FirstBox />);
function FirstBox() {
let data = "Hello world"
return (
<SecondBox>
<ThirdBox>
<FourthBox data={props.data} />
</ThirdBox>
</SecondBox>
)
}
function SecondBox(props) {
return props.children;
}
function ThirdBox(props) {
return props.children;
}
function FourthBox(props) {
return <p>Data: {props.data}</p>
}
This reduces the complexity of each parent component as they don't need to know which child component to pass props to, they can pass the entire child component downwards.
Like above, SecondBox
does not need to know about ThirdBox
nor does it need to know about FourthBox
and so on.
This way, you can create composable components for yourself in your apps using only the components you need and passing children components (using props on a nesting level) instead of the props themselves.
Let's Connect
Be it work, collaboration or just to say "hey", you can reach me using the links below
Thanks for reading.
Jeffrey