I have multiple layers of components and want to pass multiple values from the top component down to the bottom component. I am trying to make the middle and bottom component as flexible as possible so I didn't explicitly write out each parameter it can accept. How could I achieve this? Thanks.
...
export const Top = () => {
return(
<Middle
botA={propA = true, propB = false} // Props cannot be
botB={propA = 1, propB = 2} // passed like this
/>
);
}
...
export const Middle = ({botA, botB}) => {
return(
<BottomA {...botA} />
<BottomB {...botB} />
);
}
...
export const BottomA = ({...unknownProps}) => {
// Do something with unknownProps
return(
...
);
}
...
export const BottomB = ({...unknownProps}) => {
// Do something with unknownProps
return(
...
);
}
Your question appears to be about how to specify a props object to be passed as a prop itself. First, specify an object with the props to be passed on to the component, and second, pass this object as a prop to the middle component.
export const Top = () => {
return(
<Middle
botA={{ propA: true, propB: false }}
botB={{ propA: 1, propB: 2 }}
/>
);
}
The middle child destructures the props and then spreads them into the appropriate child component.
export const Middle = ({ botA, botB }) => {
return(
<BottomA {...botA} /> // ...{ propA: true, propB: false }
<BottomB {...botB} /> // ...{ propA: 1, propB: 2 }
);
}
Child components destructure the props they know about, spread the rest into a prop, i.e. one you are calling unknownProps
.
export const BottomA = ({ propA, propB, ...unknownProps }) => {
return(
...
);
}
If you find yourself continually passing props like this through intermediate components, a problem known as "props drilling", then you may want to explore the React Context API. This is an API and design pattern to resolve/alleviate the issue of explicit/implicit passing of props to intermediate components that don't know about them, and frankly probably shouldn't.
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.