Reputation: 1324
I'm building a sidebar component with React Transition Group. The relevant code goes as follows:
function FirstChild(props) {
const childrenArray = React.Children.toArray(props.children);
return childrenArray[0] || null;
}
class Sidebar extends Component {
componentWillEnter(cb) { console.log('entering'); cb() }
componentWillLeave(cb) { console.log('leaving'); cb() }
render() {
// return sidebar jsx
}
}
class Nav extends Component {
...
toggleSidebar() {
const newState = !this.state.show;
this.setState({ show: newState })
}
render() {
return (
<TransitionGroup component={FirstChild}>
{ (this.state.show == true) ? <Sidebar /> : null }
</TransitionGroup>
)
}
}
The problem is that when I try to toggle the sidebar, none of the lifecycle hooks are being triggered. On the first click, the sidebar is added to the DOM and componentDidMount is called but not componentWillEnter. When I click again to hide it, state.show gets set correctly to false but the sidebar doesn't hide and no lifecycle hooks are triggered this time.
I'm wondering if I did the ternary operator correctly to conditionally render Sidebar or if the reason is because I'm only rendering one child under TransitionGroup (for that, I used the FirstChild method found here).
Upvotes: 2
Views: 527
Reputation: 1324
The issue was in the rendering logic. For some reason
{ (this.state.show == true) ? <Sidebar /> : null }
wouldn't trigger the TransitionGroup lifecycle functions like ComponentWillEnter / ComponentWillLeave but changing it to
{ this.state.show && <Sidebar }
fixed that.
Upvotes: 1