3

I am trying to show a line of text that is stored in the state as "story" and every time state (text) changes i want the animation to run. The problem is that the animation runs on page load, but not after the state has changed. I have looked into React Transition Team and some other methods such as removing and re-adding the animation from the css, but nothing seems very elegant when i work with styled-components.

What would be the most elegant way to solve this problem with styled-components?

Below is a snippet from my code with the styled-components animation and render method.

const keyframe = keyframes`
  0% {
    letter-spacing: 1em;
    -webkit-filter: blur(12px);
            filter: blur(12px);
    opacity: 0;
  }
  100% {
    -webkit-filter: blur(0px);
            filter: blur(0px);
    opacity: 1;
  }
`

const Story = styled.h2`
  -webkit-animation: ${keyframe} 0.7s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
  animation: ${keyframe} 0.7s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
`

 render() {
   return (
            <Wrapper>
              <TextWrapper>
                <Story state={this.state.currentStory}>{this.state.currentStory}</Story>
              </TextWrapper>
            </Wrapper>
          );

1 Answer 1

5

You need to force React to unmount and remount your component when the currentStory changes.

Try this:

render() {
    const story = this.state.currentStory
    return (
        <Wrapper>
          <TextWrapper>
            <Story key={story} state={story}>{story}</Story>
          </TextWrapper>
        </Wrapper>
      );

As the key changes, React treats each one as a new component.

Here's a quick'n'dirty sandbox

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.