Search code examples
reactjsanimationreact-routersingle-page-applicationfadein

How to add fade-in animation to a component when it is loaded in react


I have an app with a nav bar and I have added react-router to app.js with routes to all the different components. I have use NavLink on all navigation buttons, so no reloads. Now, I want to add fade-in animation to a component when I mount it(press the navigation button for it)

I have no idea if it's even possible like this. I know of ways to make it work but then I have to change the entire navigation and also structure of the app.


Solution

  • That's definitely doable and shouldn't require changing the structure of your application at all! You'll just need to make use of CSS Animations.

    For a quick example, using this CSS and adding className={'example-style'} would give your component a fade-in animation lasting 3 seconds:

    .example-style {
      animation: fade-in 3s;
    }
    
    @keyframes fade-in {
      from {
        opacity: 0;
      }
      to {
        opacity: 100;
      }
    }
    

    To see it in action, check out this code sandbox.

    Hope that helps!