Reputation: 1964
I'm pretty new to React and Redux so I may be doing this completely the wrong way, in fact judging from a few other answers to similar questions on here I suspect I'm doing quite a lot wrong.
I've got a button in my 'Layout' component which adds a class to a div, this class comes from a state. The button is a toggle and will turn the state & class on and off (this will result in making a menu appear and dimming the rest of the page).
However I also want any interaction with the 'Nav' component (which lives inside a 'Header' component which in turn lives in 'Layout') to also toggle the state & class (so clicking a link collapses the menu). In jQuery/VanillaJS this was incredibly easy but I can't seem to work out the React/Redux way of doing this.
Layout Component: https://pastebin.com/WzpbeSw7
Header Component: https://pastebin.com/c34NFtUx (probably not relevant but here for reference)
Nav Component: https://pastebin.com/EsJDuLQc
Upvotes: 2
Views: 1104
Reputation: 159
One way to achieve this is to do the following:
In Layout component:
<Header / >
to: <Header handleNavClick={this.toggleNav.bind(this)} / >
In Header component:
<Navigation position="header" />
to: <Navigation closeNav={this.props.handleNavClick.bind(this)} position="header" />
In Navigation component:
return <li key={item._id}><Link to={item.slug}>{item.name}</Link></li>
to: return <li key={item._id}><Link to={item.slug} onClick={this.props.closeNav.bind(this)}>{item.name}</Link></li>
Passing the props in this way will allow you to reference reference the toggleNav function inside of Layout and then will update the state accordingly.
*** Note, you may get a binding error such as React component methods may only be bound to the component instance.
.
this.props.closeNav
directly. You would need to create a function in Navigation like this: closeNav() { this.props.closeNav.bind(this) }
. Don't forget to update the function on the <Link />
component to this.closeNav.bind(this)
Upvotes: 1
Reputation: 7308
By using redux :
You can have a state like toggleBlaBla : "show" . If you connected your react component to state of redux by using react-redux , whenever you dispatch an action for changing toggleBlaBla to "hide", your connected component will rerender.
By using only react :
If you want two components to change some ui state by some events, it is a good idea to put them in a container component, so that whenever your state changes these two components rerender with your changed state passing to both components.
Upvotes: 1