DigitalOcean offers cloud products for every stage of your journey. Begin with$200 free credit!
You know how some websites and web apps have that fancy native feel when switching between two pages or views? Sarah Drasner showed somegood examplesand including onesee Librarytear.
These animations are the kind of features that can turn a good user experience into a great one. But to achieve this in a React stack, you need to couple crucial parts into your app: the routing logic and the animation tools.
Let's start with the animations. We're going to build with React, and there are great opportunities that we can take advantage of. especially thereaction transition groupis the official package that handles elements going in and out of the DOM. Let's look at some relatively simple patterns that we can apply, even to existing components.
Transitions with the reaction transition group.
First, let's get acquainted with this.reaction transition groupLibrary to explore how we can use them to move elements in and out of the DOM.
Individual component transitions
As an example of a simple use case, we could try animating a modal or dialog, you know, the kind of element that benefits from animations that allow for smooth entry and exit.
A dialog component might look like this:
import React from "react";class Dialog erweitert React.Component { render() { const { isOpen, onClose, message } = this.props; return ( isOpen && ( <div className="dialog--overlay" onClick={onClose}> <div className="dialog">{message}</div> </div> )); }}
Please note that we use theIt's open
prop to determine if the component is rendering or not. Thanks to the simplicity of the newly modified API provided by the React-Transition-Group module, we can add a CSS-based transition to this component without much overhead.
The first thing we need to do is wrap the entire component in anothertransition group
Component. In it we save the support to mount or unmount the dialog that we include in aCSSÜbergang
.
importar Reagir de „reagir“; importar { TransitionGroup, CSSTransition } de „react-transition-group“; Klassendialog erweitert React.Component { render() { const { isOpen, onClose, message } = this.props; return ( <TransitionGroup componente={null}> {isOpen && ( <CSSTransition classNames="dialog" timeout={300}> <div className="dialog--overlay" onClick={onClose}> <div className="dialog" >{mensaje}</div> </div> </CSSTransition> )} </TransitionGroup> ); }}
Every timeIt's open
is modified, a series of class name changes are made to the root element of the dialog.
if we put themclass names
support to"discard"
, afterfade in
is added immediately before the element is assembled, and thenfade in active
when the transition begins. we must seeFade-Enter-Done
when the transition is complete, depending on thetime up
this has been established. Exactly the same will happen with thesalida
group of class names at the time the element is unmounted.
That way, we can easily define a set of CSS rules to declare our transitions.
.dialog-enter { opacity: 0.01; transform: scale(1.1); }.dialog-enter-active { opacity: 1; transform: scale(1); transition: every 300ms;}.dialog-exit { opacity: 1; transform: scale(1); }.dialog-exit-active { opacity: 0.01; transform: scale(1.1); transition: every 300ms;}
JavaScript transitions
If we want to orchestrate more complex animations using a JavaScript library, we can use thiscross
component in place.
This component does nothing for us like thisCSSÜbergang
it did, but it shows hooks on every transition loop. We can pass methods to each hook to perform calculations and animations.
<TransitionGroup-Komponente={null}> {isOpen && ( <Transition onEnter={node => animateOnEnter(node)} onExit={node => animateOnExit(node)} timeout={300} > <div className="dialog- - superposición" onClick={onClose}> <div className="dialog">{mensaje}</div> </div> </Transition> )}</TransitionGroup>
Cada gancho pasa el nodo como el primer argumento de la devolución de llamada; esto da control de cualquier mutación que queramos cuando el elemento está montado o desmontado.
routing
The React ecosystem offers several router options. will wearreact-router-dombecause it's the most popular option, and because most React developers are familiar with the syntax.
Let's start with a basic route definition:
import React, { Component } from 'react'import { BrowserRouter, Switch, Route } from 'react-router-dom'import Home from '../views/Home'import Author from '../views/Author'import Acerca de from '../views/About'import Nav from '../components/Nav'class App erweitert Component { render() { return ( <BrowserRouter> <div className="app"> <Switch> <Routegenauer Pfad= " /" componente={Inicio}/> <Ruta ruta="/autor" componente={Autor} /> <Ruta ruta="/acerca de" componente={Acerca de} /> </Switch> </div> </ BrowserRouter > ) }}
We want three paths in this app: home, author, and about.
ThatBrowserRouter
The component handles browser history updates whileExchange
decide whichList
element to render depending onLargo
Support support. Here it iswhichany transition:
oil and water
While react-transition-group and react-router-dom are excellent and useful packages for their intended uses, mixing them together can break their functionality.
For example, himExchange
Component in the direct fallback react router domList
the children and thetransition group
Wait for components in the reaction transition groupCSSÜbergang
ocross
Components can also be direct children of it. So we can't pack them like we used to.
We also can't switch views using the same boolean approach as before, as this is handled internally by the React router's dom logic.
Answer key to redeem
Although the solution may not be like thiscleansedAs in our previous examples, you can use the libraries together. The first thing we need to do is move our route declaration into a render prop.
<BrowserRouter> <div className="app"> <Route render={(location) => { return ( <Switch location={location}> <Route Exact Path="/" component={Start}/> <Route path ="/author" component={Author} /> <Route route="/over" component={Over} /> </Switch> )} /></BrowserRouter>
Nothing has changed in terms of functionality. The difference is that we now have control over what is rendered each time the position in the browser changes.
In addition, React-Router-Dom offers akey
in themTalla
object each time this happens.
In case you're not familiar with them, ReactkeyIdentify elements in the virtual DOM tree. In most cases, we don't need to specify them, as React will detect which part of the DOM to change and then fix it.
<path processing={({ location }) => { const { path name, key } = return location ( <Transition Group Component={null}> <Transition Key={key}erscheinungsbild={true } onEnter={(Knoten, erscheint ) => play(Pfadname, Knoten, erscheint)} timeout={{enter: 750, exit: 0}} > <Change location={location}> <Path Exact path="/" component={Home}/> < Path path="/author" component={Author} /> <Path path="/about" component={About} /> </Switch> </Transition> </TransitionGroup > )}}/>
Constantly changing an element's key, even if its children or props haven't changed, forces React to disassemble and reassemble it from the DOM. This helps us emulate the boolean toggle approach we had before, and is important to us here because we can put a singlecross
element and reuse it for all of our display transitions so we can mix up the routing and transition components.
Inside animation function
Since transition hooks are called every time we change location, we can call a method and use any animation library to create more complex scenes for our transitions.
export const play = (caminho, nó, erscheint) => { const delay = erscheint ? 0: 0.5 lass timeline if (pathname === '/') timeline = getHomeTimeline(nodo, retraso) else timeline = getDefaultTimeline(nodo, retraso) timeline.play()}
Ourplay
The function creates a timeline here depending on the GreenSock timelineroute name
, and we can define any number of transitions for each path.
Once the broadcast timeline is createdroute name
, we play.
const getHomeTimeline = ( node , delay ) => { const timeline = new Timeline ( { pause : true } ) ; const text = node.querySelectorAll('h1 > div'); timeline .from(node, 0, { screen: 'none', autoAlpha: 0, delay }) .staggerFrom(texts, 0.375, { autoAlpha: 0, x: -25, ease: Power1.easeOut }, 0.125); ; Rückkehrzeitachse}
Each timeline method drills down into the DOM nodes of the view and animates them. You can use other animation libraries instead of GreenSock, but the important detail is that we created the timeline in advance so that our mainplay
The method can decide which route will be executed for which route.
I've used this approach in many projects, and while it doesn't pose obvious performance issues for internal navigation, I've noticed a concurrency issue between the initial construction of the browser's DOM tree and the initial animation of the route. This resulted in a visual delay in the animation when the app was first loaded.
To ensure smooth animations at all stages of the app, there is one last thing we can do.
Defining the initial load profile
This is what I found when auditing the app in Chrome DevTools after a full update:

You can see two lines: one blue and one red. blue is for themcharge
event and red dataDOMContentLoaded
🇧🇷 Both overlap with the initial animations running.
These lines indicate that the elements are being animated while the browser has not yet created the entire DOM tree or parsed the resources. The animations guarantee great acting successes. If we want anything else to happen, we'll have to wait for the browser to finish these heavy and important tasks before executing our transitions.
After trying several different approaches, the solution that really worked was to move the animation after these events; it's that easy. The problem is that we can't trust event listeners.
ventana.addEventListener('DOMContentLoaded', () => { timeline.play()})
If for some reason the event occurs before we declare the listener, the callback we pass in will never be executed and this could cause our animations to never happen and an empty view to be displayed.
Since this is a concurrent and asynchronous problem, I decided to rely on promises, but the question arose: how can promises and event listeners be used together?
Create a promise that will resolve when the event occurs. This is how you do it.
window.loadPromise = new Promise(resolve => { window.addEventListener('DOMContentLoaded', resolve)})
We can include this in the document.Kopf
or just before the tag of the script that loads the application package. This ensures that the event never occurs before the promise is created.
In addition, we may use the data exposed globallyCargoPromesa
to any animation in our app. Suppose we want to not only animate the welcome view, but also a cookie banner or application header. We can easily invoke any of these animationsthereafterthe promise has come to an endafter
along with our transitions.
window.loadPromise.then(() => timeline.play())
This approach is reusable throughout the codebase, which eliminates the problem that would arise if an event were resolved before the animations were executed. It will refer them to the browser.DOMContentLoaded
the event is over
Now notice that the animation doesn't start until the red line appears.

The difference isn't just in the profiling report: it actually solves a problem we had in a real project.
To involve
As a reminder, I've made a list of tips for myself that you might find useful when dealing with view transitions in a project:
- When an animation is running, nothing else should happen.Run animations after all resources, recovery, and business logic are complete.
- No animation is better than bad animation.If you can't get a good animation, removing it is a fair sacrifice. The content is more important and it is a priority to show it until there is a good animation solution.
- Try on slower and older devices.They will make it easier for you to spot underperforming spots.
- Create a profile and base your improvements on metrics.Instead of guessing like I did, see if you can spot where the frames are dropping or if something is wrong and fix that problem first.
Is that! Good luck animating the display transitions. Please post a comment if this raised any questions or if you've used any transitions in your app that you'd like to share!
FAQs
How do you navigate between two pages in React? ›
When you want to navigate between pages in your React application, the go-to choice is React Router. If you are not building a single page application, you can use the <a> element or Window. location object to navigate to other pages.
What is the difference between Usespring and useTransition? ›useSprings — Multiple springs mainly for lists, where each spring moves data from a to b. useTrail — Multiple springs with a single data set, one spring follows or trails behind the other. useTransition — For mount/unmount transitions (lists where items are added/removed/updated)
How do you scroll animate with React? ›- Please be sure to include animate.css (version 4 and higher) in someway in your project This can be done in a number of ways, eg: npm install --save animate.css. ...
- offset - default 150. ...
- animateIn. ...
- animateOut. ...
- duration - default 1. ...
- initiallyVisible - default false. ...
- delay - default 0.
We can create our own CSS animations through the use of keyframes which will allow us to define our animation sequences for each element. We then use that keyframe into the CSS animation property and attach it to a particular element.
How do I pass data between pages in Reactjs? ›You can use the Link component from react-router and specify to={} as an object where you specify pathname as the route to go to. Then add a variable e.g. data to hold the value you want to pass on.
What is the difference between navigation pop and goBack? ›The difference is: pop is specific to stack navigator, accepts arguments like the number of screens to pop which is relevant for the stack navigator. goBack is more general, it works in any navigator: stack, tabs drawer.
What is useTransition? ›useTransition is a React Hook that lets you update the state without blocking the UI. const [isPending, startTransition] = useTransition() Reference.
What is concurrent mode in react? ›Concurrent rendering describes how the new features (concurrent features) included in React 18 are implemented. With concurrent rendering, you can improve your app's performance by declaring some state updates as non-urgent to keep the browser responsive.
What is react spring web? ›React Spring is a spring-physics based animation library that powers most UI related animation in React. It is a bridge on the two existing React animation libraries; React Motion and Animated. Given the performance considerations of animation libraries, React Spring is the best of both worlds.
How do you animate with scrolling? ›...
Add the class when the element is scrolled into view
- Use the Intersection Observer API.
- Measure the element's offset when the user scrolls.
- Use a third-party JavaScript library that implements #1 or #2.
How do I enable scroll animation? ›
- Create a function called scrollTrigger we can apply to certain elements.
- Apply an .active class on an element when it enters the viewport.
- Animate that . active class with CSS.
scrollIntoView() The Element interface's scrollIntoView() method scrolls the element's ancestor containers such that the element on which scrollIntoView() is called is visible to the user.
What does useEffect () do in React? ›What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates.
How do you dynamically style in React? ›- Step 0: Creating a new React app with Create React App. ...
- Step 1: Using CSS Custom Properties to set colors. ...
- Step 2: Getting CSS Custom Property values in JavaScript. ...
- Step 3: Setting the value of a CSS Custom Property with JavaScript. ...
- Step 4: Updating a CSS Custom Property dynamically on React input change.
- @keyframes jump {
- 0% {transform: translate3d(0,0,0) scale3d(1,1,1);}
- 40% {transform: translate3d(0,30%,0) scale3d(.7,1.5,1);}
- 100% {transform: translate3d(0,100%,0) scale3d(1.5,.7,1);}
- }
- .jump {
- transform-origin: 50% 50%;
- animation: jump .5s linear alternate infinite;
There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.
How do you pass data between? ›- Define destination arguments.
- Use Safe Args to pass data with type safety.
- Pass data between destinations with Bundle objects.
- Pass data to the start destination.
- ProGuard considerations.
- Additional resources.
Not surprisingly, to pass data between siblings, you have to use the parent as an intermediary. First pass the data from the child to the parent, as an argument into a callback from the parent. Set this incoming parameter as a state on the parent component, then pass it as a prop to the other child (see above example).
What are the 3 types of navigation? ›Electronic navigation can be divided further into three kinds namely, Radio Navigation, Radar Navigation, and Satellite Navigation.
What are the three types of navigation schemes? ›As with different ways to describe location, there are also different ways to navigate places. Three main types of navigation are celestial, GPS, and map and compass. In order to better understand why we teach map and compass at High Trails, it is helpful to learn the basics of all three techniques.
What is the difference between useTransition and startTransition? ›
When calling useTransition() , you get back an array with exactly two elements: An isPending boolean value, telling you whether the low-priority state update is still pending, and a startTransition() function that can be wrapped around a state update to tell React, that it is a low-priority update.
What is the difference between useDeferredValue and useTransition? ›As previously stated, useTransition() wraps the state updating code, whereas useDeferredValue() wraps a value affected by the state change. You don't have to (and shouldn't) utilize both at the same time because they accomplish the same thing.
What is suspense in React? ›Suspense is not a data fetching library. It's a mechanism for data fetching libraries to communicate to React that the data a component is reading is not ready yet. React can then wait for it to be ready and update the UI.
Can there be 2 useEffect in React? ›It's perfectly fine to have have multiple useEffect.
What is multithreading in React? ›Multithreading is for algorithms you need to execute. GUI updates need to be synchronized to the UI thread (most of the time this is the main thread but not always, Windows and GTK for example can be programmed with the UI thread running not on the main thread) – slebetman. Feb 3, 2021 at 6:15.
What is the difference between async mode and concurrent mode? ›Both refers the same thing. Previously concurrent Mode being referred to as "Async Mode" by React team. The name has been changed to highlight React's ability to perform work on different priority levels. So it avoids the confusion from other approaches to Async Rendering.
Is React easier than Spring Boot? ›In summary, both Spring Boot and React JS are application development frameworks. While Spring Boot caters to the backend side of application development, ReactJS takes care of the user side. Both frameworks share the goal to make coding less complex and more flexible.
What is React lazy for? ›The React. lazy function lets you render a dynamic import as a regular component.
Why React is called SPA? ›SPA stands for Single Page Application. It is a very common way of programming websites these days. The idea is that the website loads all the HTML/JS the first time you visit. When you then navigate, the browser will only rerender the content without refreshing the website.
How do you animate jitter? ›...
Build a custom text animation
- Select the text you want to animate.
- Switch to the animate tab.
- Click on "New animation"
- Click on "Custom" to create your own animation.
- Select the animation type you want to create.
What are the three ways to animate? ›
There are a number of ways to animate: drawing by hand (flipbook), drawing and painting on transparent celluloid, stop-motion, or using a computer to create two-dimensional or three-dimensional images.
What are the types of scroll animation? ›- Long Scrolling.
- Fixed Long Scrolling.
- Infinite Scrolling.
- Tasteful Parallax Scrolling.
You can make your activity scrollable using ScrollView. Its very simple and effective to use. Just copy code of ScrollView from below and paste it in your layout xml file. You can use this ScrollView with Linear as well as Relative Layout also.
How do you auto scroll slides? ›On the toolbar, click the three-dot menu and expand the Auto-play item. Then on this menu, click the Loop option at the bottom to enable presentation looping.
How do you trigger a scroll? ›- Using the scrollbar manually.
- Using the mouse wheel.
- Clicking an ID link.
- Calling functions in JavaScript.
It is not same as scrollTo behavior. It means scrollBy always scrolls up or down further from current position. Or you can say scrollBy scrolls by distance from current pixels. Or you can say scrollBy consider current position as (0,0) and scroll further.
When should I use scrollIntoView? ›So, the scrollIntoView () method of JavaScript is used for making the invisible part visible just by scrolling the scroll bar. You can also try the JavaScript scrollIntoView () method in alternative manners.
What is Marquee in React? ›React Fast Marquee is a lightweight React component that utilizes the power of CSS animations to create silky smooth marquees. 21 February 2021.
Does useEffect trigger a Rerender? ›Let's take a step back, pause for a moment, and think about what useEffect and useState actually do. Changing state will always cause a re-render. By default, useEffect always runs after render has run.
What is the difference between useEffect and useLayoutEffect? ›The main difference between the useEffect hook and the useLayoutEffect hook is that the useEffect hook serves asynchronously, whereas the useLayoutEffect hook works synchronously. In simple words, we can say that the difference between useEffect and useLayoutEffect is in the time at which these functions are invoked.
Why not use useEffect? ›
useEffect Hook is one of the most used Hooks in React, and it always runs on each re-render by default. However, this behaviour of cleaning up or applying the effect after each render can cause performance issues.
What is dynamic rendering in React? ›Dynamic rendering is the process of serving content based on the user agent that calls it. This means serving a client-side rendered version of your site for human users and a separate, server-side version for search engines.
How do you implement dynamic routing in React? ›- Step:1. Create react application by running the command. ...
- Step:2. Install react-router-dom by running the command. ...
- Step:3. Import router in App. ...
- Step:4. Create dynamic routes and components data in the form of json array. ...
- Step:5. Create Dynamic component to print the data from json. ...
- Step:6.
- Create a react project. npx create-react-app. ...
- Create our folders and file structure.
- Now open the BasicInfo. js file and paste the below code. ...
- Now open the Form. js file and paste the below code. ...
- Now open the App. js file and paste the below code. ...
- Now open the App. ...
- Output.
Bounce Animation effect is used to move the element quick up, back, or away from a surface after hitting it.
Is CSS animation faster than JavaScript? ›The fact is that, in most cases, the performance of CSS-based animations is almost the same as JavaScripted animations — in Firefox at least. Some JavaScript-based animation libraries, like GSAP and Velocity. JS, even claim that they are able to achieve better performance than native CSS transitions/animations.
How do I navigate to another page in next JS? ›- Create a Next.js App.
- Navigate Between Pages. Pages in Next.js. Link Component. Client-Side Navigation.
- Assets, Metadata, and CSS.
- Pre-rendering and Data Fetching.
- Dynamic Routes.
- API Routes.
- Deploying Your Next.js App.
js. Approach: To navigate to another page by clicking a button we will be using the useHistory hook. UseHistory hook: This method lets you access React Router's history instance. This allows you to redirect users to a different page via the history instance.
How do you navigate to another page with props in react JS? ›If you want programmatically navigation from one page to another then you should use history. push method. In other words, we can say if you want to manage the redirection on button click then you can use it. This function will push a new entry in the history stack.
How do I redirect a page in React js? ›- import { Redirect } from 'react-router-dom'; <Route path='/redirect-page' element={ <Redirect to="/error-page" /> }/>
- import { Navigate } from 'react-router-dom'; <Route path="/redirect" element={ <Navigate to="/error-page" /> } />
What is next () in js? ›
Next. js is a flexible React framework that gives you building blocks to create fast web applications.
How to link pages using js? ›- Create an anchor <a> element.
- Create a text node with some text which will display as a link.
- Append the text node to the anchor <a> element.
- Set the title and href property of the <a> element.
- Append <a> element in the body.
The first solution to perform multiple onClick events in React is to include all of your actions inside of a function and then call that single function from the onClick event handler. Let's explore how to do that in a React Component: import React from 'react'; function App() { function greeting() { console.
How do you make a pop up React button? ›Steps to run the application: Run the below command in the terminal to run the app. Output: Example 2: In this example, we will use the reactjs-popup library to create a popup modal that appears at the click of a button and closes in the same behavior. Please update your file App.
Which element lets the user navigate to another page by clicking or tapping on it in React? ›A <Link> is an element that lets the user navigate to another page by clicking or tapping on it. In react-router-dom , a <Link> renders an accessible <a> element with a real href that points to the resource it's linking to. This means that things like right-clicking a <Link> work as you'd expect.
What is the difference between redirect and useNavigate? ›From my understanding and reading from the docs, redirect is used in actions and loaders. And useNavigate is a hook and it can only be used in React Hooks and React Components. So for example you can use useNavigate to redirect the user in your Homepage Component, for example in some state change.
What is the difference between useNavigate and useHistory? ›The useNavigate() hook is introduced in the React Router v6 to replace the useHistory() hook. In the earlier version, the useHistory() hook accesses the React Router history object and navigates to the other routers using the push or replace methods. It helps to go to the specific URL, forward or backward pages.
What is the difference between useNavigation and navigation prop? ›useNavigation is a hook which gives access to navigation object. It's useful when you cannot pass the navigation prop into the component directly, or don't want to pass it in case of a deeply nested child. useNavigation() returns the navigation prop of the screen it's inside.