nachosanchezz
nachosanchezz

Reputation: 3

React: Spring transition not behaving properly

I recently got started with both React and JavaScript. I've been reading the Spring API docs for the Transition component, and ended up with this piece of code when doing some tests. Now, I expected a smooth transition, but got the following sequence:

For what I read in the docs, I'm not able to see what I'm doing wrong here, so any help is more than welcome. I've tested different configs and always get that sequence.

PS: Content is just a plain div that takes its background color as prop, so nothing fancy there.

import React from 'react';
import './App.css';
import Content from './components/content';
import {Transition, config} from 'react-spring/renderprops';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      switch: false
    };
  }

  render() {
    return (
      <div id="container" onClick={() => {this.setState({switch: !this.state.switch})}}>
        <Transition
        config={config.slow}
        items={this.state.switch}
        from={{opacity: 0}}
        enter={{opacity: 1}}
        leave={{opacity: 0}}>
        {s => s ? () => <Content backgroundColor="rgb(37, 95, 142)"></Content>
                : () => <Content backgroundColor="rgb(37, 142, 118)"></Content>}
        </Transition>
      </div>
    );
  }
}

export default App;

Thanks!

Upvotes: 0

Views: 414

Answers (1)

Peter Ambruzs
Peter Ambruzs

Reputation: 8223

The Transtition changes the opacity in your example, but you never give the changed values to you rendered component. It missing the prop parameter in the arrow function. You should add this prop to the style property to your component.

For example:

props => (<Content props={props} backgroundColor="rgb(37, 95, 142)" />)

And the Component is something like this:

const Content = ({ backgroundColor, props }) => (
  <animated.div style={{ backgroundColor, ...props }}>Content</animated.div>
);

And now you can see the opacity change.

I also used animated.div here and added the native poperty to Transition for better performance.

Here is my example: https://codesandbox.io/s/ecstatic-wood-7p1ym?file=/src/App.js

Upvotes: 1

Related Questions