So in my main component, I send props to a child component like this:
<div className={styles.navBar}>
<MasterNavBar color={false} scrollChange={true} />
</div>
MasterNavBar gets access to the props correctly, but I need MasterNavBar to pass those props to a child component called NavBar, which I currently do like this:
<NavBar props />
However, when I do this, the props are not accessible in my NavBar component file. For example, in NavBar, doing props.color to get my color prop returns undefined. So, am I passing my props incorrectly, or am I missing something else?
CodePudding user response:
As Antonio Pantano said, you can pass the whole props to the <NavBar {...props}/>
component, but this is a bad practice way. This article explained why it is a bad practice way. So you can pass the MasterNavBar
props to its child in these two ways:
const MasterNavBar = (props) => {
/*
rest of your code
*/
return <NavBar color={props.color} scrollChange={props.scrollChange}/>
}
or
const MasterNavBar = ({color, scrollChange}) => {
/*
rest of your code
*/
return <NavBar color={color} scrollChange={scrollChange}/>
}
You can change the name of NavBar
props as you wish, and you access them in the NavBar
component by these names.
CodePudding user response:
That's depend on which props NavBar is expecting. If you don't care about typing (either with typescript or react PropTypes) you can simply do like this:
<NavBar {...props} />
However this is not the best approach and can lead to performance issues.