Reputation: 3518
Currently working a group project and I've been looking over the code the group wrote and I'm curious if there is a better way to pass props to n children components that change the state of the top-level App component.
currently we have something like this:
return (
<div>
<header className="navBar">
// NavBar is an example for the question
<NavBar
showSplash={this.state.showSplash}
displayAllSearchResults={this.displayAllSearchResults}
searchBarDisplay={this.state.showCard}
updateResults={this.updateResults}
selectResult={this.selectResult}
searchResults={this.state.searchResults}
showSuggestions={this.state.showSuggestions}
/>
</header>
<section className="App">
<article className="mainContent">{card}</article>
</section>
<div className="appBackground" />
</div>
);
All of these methods (which there are probably too many) are being passed into the NavBar
component that itself is composed with a SearchBar
component which also needs that giant block passed into it in order to change the state all the way back at the top-level App
. This feels wrong, is there a solution or better approach to passing all these props down?
Upvotes: 9
Views: 8937
Reputation: 104
If you want a data to be accessible by all the child components, then you have following options:
Or you could follow @Abdelkarim EL AMEL answer if that soughts out you issue for now.I would suggest take a look at the above mentioned options and if setting a global state which can be accessed anywhere in the app helps you to not send prop to each component explicitly. I would prefer to use a global state for variable which are common and needs to be accessed by all the child of the root app.
For example a button component to change the theme of the app. It changes the state of the root app and is accessible by every component.
Upvotes: 3
Reputation: 2635
I think this is actually entirely OK, and would recommend leaving it.
If you don't like seeing it itemized in the return of the render method you could keep them all in an object called navbarprops and just spread that in. I still prefer it as is though!
Upvotes: 2
Reputation: 1533
You can use the spread
operator like this :
<NavBar {...this.state} />
It will pass you state properties as props to the navbar.
In you Navbar component, you can get the value of showSplash
in state from props.showSplash
If you want to pass the data into a child component of Navbar, you can do something like this :
<ChildComponent {...props} /> // if Navbar is a functional component
<ChildComponent {...this.props} /> // if Navbar is a stateful component
Reference:
Here is a sample stackblitz for illustration.
Upvotes: 8