I have a dropdown BasketContents
component (as per this question), which fades in and out when a button is clicked. I also want it to close when a the route is changed by clicking a Link
tag. I.e. if it's already open on the Checkout
page, if I then click the Home
page link I want it to automatically close without clicking the basket's close button.
My Routes.js
is the root of the app:
render() {
return (
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/home" component={Home} />
<Route path="/checkout" component={Checkout} />
</Route>
</Router>
);
}
App.js
looks in part like this:
render() {
const childrenWithProps = React.Children.map(
this.props.children,
child => {
return (
React.cloneElement(child, {
basket: this.state.basket
}
)
)
}
);
return (
<div className="main">
<HeaderSection basket={this.state.basket} />
<div className="content">
{childrenWithProps}
</div>
</div>
)
}
The Basket.js
component contains the button:
constructor() {
super();
this.state = { open: false }
this.handleDropDown = this.handleDropDown.bind(this);
}
handleDropDown() {
this.setState({ open: !this.state.open })
}
render() {
return(
<div className="basket">
<button className="basketBtn" onClick={this.handleDropDown}>Toggle</button>
<BasketContents
contents={this.props.contents}
open={this.state.open}
/>
</div>
)
}
I did try adding onEnter
to my routes but understandably that doesn't do much since it doesn't have access to the Basket
's open
state. I would ideally like to set the open
state of Basket.js
to false
when changing route (i.e. when clicking on a Link
component). Is this possible?