Mastering CSS Transitions with React 18

0
39
Mastering CSS Transitions with React 18


Animations have always been a part of the web experience. The smooth transitions of a web page’s elements have always brought aesthetic appeal to websites.

Cascading Style Sheets (CSS) is the language used to design websites and make animations possible. The easiest way to implement animations with CSS is using the transition property.

We will be taking an in-depth look at CSS transitions and how to use them to create animations with React 18.

Let’s get started!

What are CSS Transitions?

CSS transitions are basic animations generated with the CSS property transition. Though easy to use, this property can perform a lot of amazing animations in a web page. CSS Transitions are not the only way animations can be implemented with CSS but happen to nonetheless be effective for most animation tasks.

React 18 introduced a new hook called useTransition(). According to the documentation, useTransition() returns a stateful value for the pending state of the transition, and a function to start it. These transitions are user interface (UI) updates, but are not animations. They have nothing to do with CSS transitions, our topic here.

Exploring the Transition properties

When making animations using CSS transitions, we use some properties to specify what we want. These include:

  • transition-property
  • transition-duration
  • transition-timing-function
  • transition-delay
  • transition

transition-property

The transition property specifies to the browser the property of the element whose styling would change, and should therefore perform a transition.

Let’s see an example: suppose we alter the width property of a particular element. Then that element should have the value width in its transition-property.

1.element {

2 transition-property: width;

3}

Now, it is not only the width property that a transition can be performed on. There are more properties a transition can be performed on. Find a complete list of the properties in this article.

Once a transition-property is selected, the browser checks for changes on that element’s property and performs the transition on it.

Note: When there are a lot of properties to be selected, one can use all as a value.

1.element {

2 transition-property: all;

3}

transition-duration

The transition-duration property specifies the time interval in which the property must complete the change.

Now, suppose we want to perform a transition shrinking the width of a div from 500px to 50px in 2 seconds after hovering on the element. The value of the transition-duration (the time it would take the animation to complete) is 2s.

1div {

2 height: 100px;

3 width: 500px;

4 background-color: #768fc5;

5 margin: 0 auto; /* So as to center the box */

6 transition-property: width;

7 transition-duration: 2s;

8}

9

10div:hover {

11 width: 50px;

12}

And we have this displayed:

It takes exactly 2 seconds for the box’s width shrink from 500px to 50px on hover.

We can achieve a fully working CSS transition with transition-property and transition-duration, as the rest of the properties are not compulsory and provide secondary features.

transition-timing-function

The transition-timing-function property helps control the acceleration of a transition. It specifies when the animation slows down and speeds up over the specified duration in transition-duration.

The values a transition-timing-function can accept are:

  • ease
  • ease-in
  • ease-out
  • ease-in-out
  • linear
  • cubic-bezier()

ease

The ease timing function is the default of any transition in CSS. It starts with a slow movement, then fast, and ends slowly. Here is an animation made with ease:

ease-in

The ease-in timing function has a slow start. Here is an illustration:

ease-out

This timing function has a slow end. This function is used if that is the effect desired. Here is an illustration:

ease-in-out

This timing function has a slow start and end. If this is the behavior desired of an animation, then this is the value to be used. Here is an illustration:

linear

This specifies a transition effect with the same speed from start to finish. Here is an illustration:

cubic-bezier()

This cubic-bezier() is a function that accepts parameters used to create a custom transition-timing-function apart from the earlier specified ones. Using cubic-bezier is beyond the scope of this article; therefore, read this article to learn more.

transition-delay

The transition-delay property specifies the time interval the transition is delayed before it finally occurs. The value is in seconds: 2s, 1s, 1.5s, etc. Here is an illustration in which the transition is delayed for 1.5s before it works.

transition

The transition property is a short form for all the earlier mentioned transition properties. The syntax is

1element {

2 transition: <property> <duration> <timing-function> <delay>;

3}

An example: suppose we wanted to perform a transition with property height changing, in 2s, with a linear timing function and a delay of 0.5s, then it would be written this way:

1element {

2 transition: height 2s linear 0.5s;

3}

Another example: suppose an element has more than one transition-property. In that case, the transition contains the value of the first transition, then a comma ,, and finally the second transition value.

1element {

2 transition: height 2s linear 0.5s, width 1s ease-in 0s;

3}

Open Source Session Replay

OpenReplay is an open-source alternative to FullStory and LogRocket. It gives you full observability by replaying everything your users do on your app and showing how your stack behaves for every issue. OpenReplay is self-hosted for full control over your data.

replayer.png

Happy debugging for modern frontend teams – start monitoring your web app for free.

Creating a Day and Night Mode Toggle

Step 1: Set up a React JS Project

1npx create-react-app toggle

Step 2: Edit the index.js

1import React from 'react';

2import { createRoot } from 'react-dom/client';

3import App from './App'

4const container = document.getElementById('root');

5const root = createRoot(container);

6

7root.render(<App />);

Step 3: Edit the App.js

1import React, {useState} from "react";

2import "./style.css";

3

4export default function App() {

5 let [mode, setMode] = useState("light");

6 function handleClick(){

7 setMode(mode == "light" ? "dark" : "light");

8 }

9 return (

10 <div className={'app ' + mode}>

11 <h1>This is a Day/Night Toggle Website</h1>

12 <div className="btn-box">

13 <button onClick={handleClick}>Toggle</button>

14 </div>

15 </div>

16 );

17}

*Step 4: Add some styling to style.css

1* {

2 margin: 0;

3 padding: 0;

4}

5

6.app {

7 height: 100vh;

8 transition-property: background-color;

9 transition-duration: 1s;

10 transition-timing-function: linear;

11 /* No transition delay */

12}

13

14.light {

15 background-color: white;

16 color: black;

17}

18

19.dark {

20 background-color: #05040f;

21 color: white;

22}

23

24h1 {

25 font-family: Cambria;

26 text-align: center;

27 padding: 50px;

28}

29

30.btn-box {

31 text-align: center;

32}

33

34button {

35 padding: 10px;

36}

And we have this beautiful transition:

Link to live project: https://stackblitz.com/edit/react-dc58ms

Creating A Modal Animation

Let’s see a different example, and create a modal animation.

Step 1: Set up a React JS Project

1npx create-react-app modal-transition

Step 2: Edit the index.js

1import React from 'react';

2import { createRoot } from 'react-dom/client';

3import App from './App'

4const container = document.getElementById('root');

5const root = createRoot(container);

6

7root.render(<App />);

Step 3: Edit the app.js

1import React, {useState} from "react";

2import "./style.css";

3

4export default function App() {

5 let [view, setView] = useState(false);

6 function show() {

7 setView(true);

8 }

9 function close() {

10 setView(false);

11 }

12 return (

13 <div>

14 <div className="modal" style={{top: view && "5px"}}>

15 <p className="modal-header">This is a Modal Header</p>

16 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nisl eros, pulvinar facilisis justo mollis, auctor consequat urna. Morbi a bibendum metus. </p>

17 <div className="btn-box">

18 <button onClick={close}>Close</button>

19 </div>

20 </div>

21 <div className="btn-box">

22 <button onClick={show}>Show Modal</button>

23 </div>

24 </div>

25 );

26}

Step 4: Add some styling to the style.css

1body {

2 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

3}

4

5.modal {

6 max-width: 400px;

7 min-height: 200px;

8 padding: 10px;

9 background-color: whitesmoke;

10 position: fixed;

11 left: 0;

12 right: 0;

13 margin: 0 auto;

14 top: -250px;

15 transition: top 0.5s ease-out;

16 z-index: 1;

17}

18

19.modal-header {

20 font-size: 20px;

21 text-align: center;

22 padding-bottom: 20px;

23 font-weight: bold;

24}

25

26.btn-box {

27 text-align: center;

28}

29

30button {

31 padding: 10px;

32}

And now we have this animation:

Link to live Project: https://stackblitz.com/edit/react-blgxpk

Creating a progress bar

For our final example, let’s build a progress bar, a common feature.

Step 1: Set up a React JS Project

1npx create-react-app progress-bar

Step 2: Edit the index.js

1import React from 'react';

2import { createRoot } from 'react-dom/client';

3import App from './App'

4const container = document.getElementById('root');

5const root = createRoot(container);

6

7root.render(<App />);

Step 3: Edit the App.js

1import React, {useState} from "react";

2import "./style.css";

3

4export default function App() {

5 let [distance, setDistance] = useState('0');

6 function move(){

7 setDistance('100%');

8 }

9 return (

10 <div>

11 <h1>Progress Bar</h1>

12 <div className="progress-box">

13 <div className="mover" style={{width: distance}}></div>

14 </div>

15 <div className="btn-box">

16 <button onClick={move}>Load Progress Bar</button>

17 </div>

18 </div>

19 );

20}

Step 4: Add some styling

1body {

2 font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;

3 text-align: center;

4}

5

6.progress-box {

7 height: 50px;

8 width: 500px;

9 background-color: #8f8fa3;

10 margin: 10px auto;

11}

12

13.mover {

14 background-color: #222274;

15 width: 0;

16 height: inherit;

17 transition: width 1s linear 1s;

18}

19

20button {

21 padding: 20px;

22}

And we have this:

Link to live project: https://stackblitz.com/edit/react-swfomx

Conclusion

With these exercises, we have explored several uses of CSS transitions. CSS transitions serve front-end developers in making simple animations and can be combined with any Javascript framework to bring out the best in websites.

References



Source link

Leave a reply

Please enter your comment!
Please enter your name here