React fade in element

GluePear picture GluePear · Jan 25, 2017 · Viewed 35k times · Source

I have a Basket component which needs to toggle a BasketContents component when clicked on. This works:

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}>
                    Open
                </button>
              {
                this.state.open
                ?
                <BasketContents />
                : null
              }
            </div>
        )
    }

It uses a conditional to either display the BasketContents component or not. I now want it to fade in. I tried adding a ComponentDidMount hook to BasketContents to transition the opacity but that doesn't work. Is there a simple way to do this?

Answer

Giladd picture Giladd · Jan 25, 2017

An example using css class toggling + opacity transitions:
https://jsfiddle.net/e7zwhcbt/2/

Here's the interesting CSS:

.basket {
  transition: opacity 0.5s;
  opacity: 1;
}
.basket.hide {
  opacity: 0;
  pointer-events:none;
}

And the render function:

render() {
    const classes = this.state.open ? 'basket' : 'basket hide'
    return(
      <div className="basket">
        <button className="basketBtn" onClick={this.handleDropDown}>
          {this.state.open ? 'Close' : 'Open'}
        </button>
        <BasketContents className={classes}/>
      </div>
    )
  }