Kaiser Soze
Kaiser Soze

Reputation: 1498

Animate conditionally React component with react-spring

I have a react component and I want to animate it when the state of the component change.

I am using useReducer const [state, dispatch] = useReducer(reducer, initialState); Then on click I update the state.isOpen from false to true or vice versa. In the same component I have this

const wrapperStyles = useSpring({
    transform: state.isOpen ? 'translate3d(0, 0, -300px)' : 'translate3d(0, 0, 0)'
  });

Finally the component consumes it like this <StyledWrapper style={wrapperStyles}> I expect the transform the be applied and changed when the state changes, but it does not. I have no idea what I am doing wrong, I am following their simple instructions on the website.

Edit: I tried with opacity instead of transform and it works fine, so I am doing something wrong with the css transform?

Upvotes: 0

Views: 1916

Answers (2)

Kaiser Soze
Kaiser Soze

Reputation: 1498

I am answering my own question, so the reason why it wasn't working is that I was using different values.

from 0 to 300px. It must be the same value so changing to transform: state.isOpen ? 'translate3d(0, 0, -300px)' : 'translate3d(0, 0, **0px)**' where 0px makes the difference :)

Thanks for the help!

Upvotes: 1

seunggabi
seunggabi

Reputation: 1822

You read this page.
I search react-spring,
If you use transform, You use import {useTransition, animated} from 'react-spring'

not useSpring()

https://www.react-spring.io/docs/hooks/use-transition

const [items, set] = useState([...])
const transitions = useTransition(items, item => item.key, {
from: { transform: 'translate3d(0,-40px,0)' },
enter: { transform: 'translate3d(0,0px,0)' },
leave: { transform: 'translate3d(0,-40px,0)' },
})
return transitions.map(({ item, props, key }) =>
<animated.div key={key} style={props}>{item.text}</animated.div>
)

Upvotes: 0

Related Questions