Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React fade in element

Tags:

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?

like image 391
GluePear Avatar asked Jan 25 '17 13:01

GluePear


People also ask

How do you make a div appear slowly in react?

Just use a conditional class and CSS. Have a state variable like visible . So depending upon the state. visible the input will have a class of either fadeIn or fadeOut .

How do you make something fade in CSS?

In the CSS, use the @keyframes rule paired with fadeIn. At 0%, set the opacity to 0. At 100%, set the opacity to 1. This creates the fade-in effect.


2 Answers

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

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>
    )
  }
like image 86
Giladd Avatar answered Oct 14 '22 04:10

Giladd


I would use react-motion like this:

<Motion style={{currentOpacity: spring(this.state.open ? 1 : 0, { stiffness: 140, damping: 20 })}}>
    {({currentOpacity}) =>
        <div style={{opacity: currentOpacity}}>
            <BasketContents />
        </div>
    }
</Motion>

I haven't tested it, but it should work.

like image 45
Michal Cumpl Avatar answered Oct 14 '22 03:10

Michal Cumpl