Barba.js provides a smooth fluid transition between the website’s page and within a short period of time, it has built a good reputation in the market with more than 8K hits on their source code. Yet, The hard part is to integrate it with modern frameworks. As we all know, in today’s world the craze for SPA using frameworks like React/Vue has only increased. The design is made up of a single page using React/Vue works smoothly and provides a native feel with higher UX. The SPA created with these frameworks can provide all sorts of virtual routing without changing the HTML structure but it rearranges the components. To achieve the effect of transitioning between the route change in React is super interesting as we can leverage the lifecycle hooks to produce the same effect as Barba.js without using the package.
In this article, the Single page React application is designed where the routing is achieved using ‘react-router’ and the transitions are produced with ‘GSAP’. The app is constructed using create-react-app setup where additional discrepancies i.e. react-router and GSAP are installed. The simple folder structure looks like below snippet below where two stateless components, **Contact **and **Home **are present which is being operated by App.js.
App.js
- Home Component (Route= "/")
- Contact Component (Route= "/contact")
These components are stateless, providing leverage of using two critical hooks ( useRef/useEffect ) to animate while mounting and removing the component. The typical HTML structue for each component consists of the first layer i.e. the loading screen, and the entire child components/ HTML structure as a second layer. So, while entering the component using useEffect hook, the loading screen will be animated with GSAP timeline, and the return statement in useEffect will be useful to provide us an enhanced experience of animation while unmounting the component from DOM tree.
The simple steps to build the transition are as below:
GSAP Timeline for Sliding Effect
Timeline is a powerful class providing all features of setting up a sequential animation for multiple elements. Here, using a timeline, the sliding animation can be achieved with the help of sequential execution of below 4 steps.
#barba #gsap #animation #react #javascript