2

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).

cheng
  • 1,264
  • 2
  • 18
  • 41
  • I cannot find componentWillEnter in docs https://facebook.github.io/react/docs/react-component.html ... where did you get it? – Melounek Jul 27 '17 at 07:49
  • @Melounek https://medium.com/appifycanada/animations-with-reacttransitiongroup-4972ad7da286 – cheng Jul 27 '17 at 17:54
  • Right... I simulated it and for me its "entering" and "leaving" properly. Are you sure you provided all of code? For example if you are using connect() there can be this problem: https://stackoverflow.com/questions/37092116/reacttransitiongroup-doesnt-works-with-react-redux-connected-component – Melounek Jul 28 '17 at 09:15
  • @Melounek hm nope, not using Redux for this. For the animations I'm using Greensock but I don't think that should matter either. – cheng Jul 28 '17 at 19:28

1 Answers1

1

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.

cheng
  • 1,264
  • 2
  • 18
  • 41