Create Animated React Apps With React Spring

One thing that is pivotal to creating great interactive web applications is animations. Animations add life to your applications and improve the overall user experience.

One thing that is pivotal to creating great interactive web applications is animations. Animations add life to your applications and improve the overall user experience.


Table of Contents

In this tutorial, we'll be looking at how to create simple yet lovely animations in your React apps using an npm package called react-spring, specifically, the Spring component of the package.

React Spring is a great animation package that has been endorsed by some of the React core team including Dan Abramov, and is generally considered one of the best animation packages for React apps out there. It utilises spring like physics in its core animations making it easy to configure. In this tutorial we'll be focused on the Spring component which is one of react-spring's easier to use and more flexible components.

With Spring we are able to:

  • Manipulate values(numbers)of any sort from measurement units to actual data.

  • Manipulate HTML attributes
  • Manipulate SVG paths
  • Adjust CSS

And much more!

Springs are cumulative, meaning they'll remember all values passed to them. Let's look at how we can get started with Springs, complete with an example making use of the newly announced React Hooks.


Examples


What We'll Build

We'll be building a simple sliding and fading animation to show you how easily you can achieve animations.


Setting Up

We'll be setting up our React environment with create-react-app which will also generate some boilerplate code that will allow us to get started. To install it run

npm install -g create-react-app

Now you can use it to create your app. Run:

create-react-app react-spring-demo

A folder named react-spring-demo will be created containing our project. Cd into that directory and install our primary dependency, the react-spring package by running:

yarn add react-spring

You will notice we're using yarn as the package manager for this project as it is the default package manager used by create-react-app. Make sure to have yarn installed by running


npm install -g yarn

We are now set up to go, let's create our first animated page.


Animating Styles

Spring can be used to animate styles, to do this, we'll use it to animate the transition into a newly loaded page. To do this we'll wrap the jsx context of App.js in a Spring component.

The Spring component will take two props, from and to which represents the values to be interpolated by our animation.

In our case we want to create the effect of a page dropping down from above and fading in. To do this, we'll set the initial top margin of the page elements to be a negative value and bring it to 0 during the animation creating a dropping motion. To create the fade in effect, we'll set the initial value of the opacity to 0 and bring that value to 1 at the end of the animation. Luckily for us, the boilerplate generated by create-react-app has the perfect background to show this effect at work so we won't need to change it for now.

This is what it will look like in our App.js file:


App.js

// import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import { Spring } from 'react-spring'; class App extends Component { render() { return ( <Spring from={{ opacity: 0, marginTop: -1000 }} to={{ opacity: 1, marginTop: 0 }}> { props => ( <div className="App" style={ props }> <div > <header className="App-header" > <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://l.morioh.com/b0a3f595aa?r=https://reactjs.org" rel="nofollow" target="_blank" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> </div> ) } </Spring> ); } } export default App;

Now fire up your application by running this command.

yarn start

Your browser will open up and you should see the page load with the contents having the desired drop and fade in animations.

Nice, isn't it? You can use spring to create any even more style animations adjusting a variety of styles. It is however advised to stick to animating opacity and translations to keep your app light.


Animating innerText

Animating styles is great but we can also use Spring to animate the value of contents shown on the screen. To show this, we'll be creating a counter that starts at 0 and ends at 10 using Spring. As expected, from will hold our initial value and to will hold the final value to be displayed.

Under the src directory, create a folder called components and in it a file called Counter.jsx. Add the following code to Countrt.jsx :

//src/Counter.jsx import React from 'react'; import { Spring } from'react-spring'; const counter = () => ( <Spring from={{ number: 0 }} to={{ number: 10 }} {props => <div>{props.number.toFixed()}</div>} </Spring> ) export default counter;

Now import our counter into App.js and add it under the header element to render it in our app.

//App.js ... import Counter from './components/Counter'; class App extends Component { render() { return ( <Spring from={{ opacity: 0, marginTop: -1000 }} to={{ opacity: 1, marginTop: 0 }}> { props => ( <div className="App" style={ props }> <div > <header className="App-header" > <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> <Counter /> </header> </div> </div> ) } </Spring> ); } } export default App;

Opening up your browser you will notice the counter just under the Learn React text, like this: Just one catch, our animation is happening so soon that we are missing most of it as it occurs while our initial page is animating into visibility. Luckily, we can delay our animation by adding a delay prop which will be equated to a value in milliseconds, this is the amount of time our animation will wait before starting. Adding a 1 second delay, the counter function will now look like this:

const counter = () => ( <Spring from={{ number: 0 }} to={{ number: 10 }} delay= '1000'> {props => <div>{props.number.toFixed()}</div>} </Spring> )

Checking the browser, the counter now starts after the page animations are finished. Another method we can use to add this delay is through the config prop which we'll come to when discussing the Spring configurations shortly.


Spring config

As mentioned before,Springs are physics based. This means we don't have to manually deal with durations and curves. This is great as it takes away some of the heavy math we may have to cover. However, we can still adjust the behaviour of our Spring by tweaking it's tension, friction, delays, mass and other behaviour through the config prop.

Don't wish to deal with this but still want to adjust your animations? Don't worry, react-spring comes with some inbuilt presets that we can use to tweak our Springs. All we have to do is import config from the react-spring package and feed them to the config prop of the Spring. Before we get confused about which config is which, let's take a look at an example.

import React from 'react'; import { Spring, config } from'react-spring'; const counter = () => ( <Spring from={{ number: 0 }} to={{ number: 10 }} delay= '1000' config = { config.molasses }> {props => <div>{props.number.toFixed()}</div>} </Spring> ) export default counter;

In the example above, we've used the molasses preset which is a high tension, high friction preset provided by react-spring . The presets typically define the tension and friction properties of out Spring. These presets include molasses, default, slow, stiff and wobbly.

While the presets only define the tension and friction, you can manually configure other properties of the Spring animation which include but are not limited to delay, mass, velocity and duration. For a full list of properties you can configure, along with other options that can be passed as props, check out this page.


Usage With Hooks

The React team recently introduced React Hooks, this allows us to create functional components that can permanently store data and cause effects, basically adding state to functional components. Hooks are currently only available in React 16.7 alpha as we await a stable release. To use hooks you will need to upgrade to the 16.7 alpha versions of react and react-dom.

To do this, run the following commands:

yarn remove react-dom && yarn add [email protected] yarn remove react && yarn add [email protected]

We can use hooks out of the box with react-spring which exports a hook called useSpring. This hook allows us to define and update data and will generally consist of the same values you would pass as props and useSpring will turn it into animated data. To showcase this, let's look at how we can have more text rendered after our previous animations are done animating.

Here's how we can do that, let's create a new component file called Hooks.jsx and add the following code.

//Hooks.jsx import React from 'react'; import { useSpring, animated } from 'react-spring'; const HookedComponent = () => { const [props] = useSpring({ opacity: 1, color: 'white', from: { opacity: 0 }, delay: '2000' }) return <animated.div style={props}>This text Faded in Using hooks</animated.div> } export default HookedComponent;

We pass the spring settings as an object of arguments to useSpring which will then pass these values to the animated element that then creates our animated spring. We've set our delay to 2000ms to ensure the text from our hooked component fades in after the counter is finished.

Now let's import this into App.js and use the HookedComponent in our app. After cleaning up some of the initial boilerplate code from `create-react-app`, it should end up looking like this: Fire up your final application an see the magic.


Conclusion

You now have the tools to get started using react-spring. While it's the easiest to use component of react-spring, Spring provides a simple yet effective means of animating React applications while taking away a huge amount of the workload from the developer.

Here's the CodeSandbox:


You can build on Spring by making use of react-spring's other components such as Transition which animates component lifecycles and Trail which animates the first element of an array and has the rest follow it in a natural trail. Overall, react-spring is a great package with a variety of options depending on your animation needs.

Full-stack Reactive Java with Spring Framework, Spring Boot and Project Reactor

Full-stack Reactive Java with Spring Framework, Spring Boot and Project Reactor

Reactive programming offers Java developers a way to build message-driven, elastic, resilient, and responsive services...yet many Java developers don't know where to begin.

Reactive programming offers Java developers a way to build message-driven, elastic, resilient, and responsive services...yet many Java developers don't know where to begin.

The Reactive Streams initiative provides a baseline and Project Reactor provides a great way to become immediately productive, leveraging reactive capabilities from end to end. Whether you're coming from a Spring MVC environment or a functional perspective, Reactor empowers you to spin up fully reactive Spring Boot 2 applications quickly and efficiently.

In this talk, the presenter dives into the net-new Netty-based web runtime and shows you how to:

  • integrate easily with existing Spring-stack technologies
  • easily transition from blocking to reactive applications & systems
  • define your API in an imperative style and functionally, reaping all benefits both ways
  • leverage powerful new testing mechanisms to make code better and life easier

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Java Spring Framework and Spring Boot

Java Programming Masterclass for Software Developers

100+ Java Interview Questions and Answers In 2019

Build a microservices architecture with Spring Boot and Spring Cloud

Spring Framework - Top 50 Questions for Interview In 2019

Building a Simple CRUD App using Spring Boot, MySQL, JPA/Hibernate

Full Stack Web Development with Angular and Spring MVC

Spring Boot Tutorial For Beginner- Spring Boot Full Course

Spring Boot Tutorial For Beginner- Spring Boot Full Course

This "Spring Boot Tutorial For Beginner- Spring Boot Full Course" video will help you learn Spring Boot Framework from scratch with examples. This Spring Tutorial is ideal for both beginners as well as professionals who want to master the Spring Boot Framework

Spring Boot Full Course - Learn Spring Boot In 4 Hours | Spring Boot Tutorial For Beginner

Below are the topics covered in this Spring Boot Tutorial for Beginners video:

1:40 What is Spring Boot?
2:35 Features of Spring Boot
3:50 Why Do We Need Spring Boot?
4:30 Spring Boot Market Trend
5:15 Spring vs Spring Boot
6:25 Install & Setup Spring Boot
6:45 System Requirements
7:35 Install & Set up Spring Boot CLI
14:00 Install & Setup Spring Tool Suite
25:40 Model View Controller
26:00 What is MVC?
27:35 Model View Controller Workflow
29:00 What is Dependency Injection?
31:50 Inversion of Control
33:10 Types of Dependency Injection
34:05 Benefits of Dependency Injection
48:35 Auto wire
49:50 Create First Web Application Using Spring Boot
1:06:50 Create a Web Application To Pass Client Data
1:13:40 Model View & Object Example
1:20:30 Create a Submission Form In Spring Boot
1:40:50 Connect Web Application To Database
2:04:50 REST API
2:07:35 What is REST API?
2:08:50 Features of REST API
2:09:35 Principles of REST API
2:11:40 Methods of REST API
2:12:20 REST API Hands-On
2:35:55 Spring Data REST
2:36:55 Spring Data REST Hands-On
2:46:35 Spring Security
2:47:30 Secure Applications Using Spring Boot
2:58:56 Spring Boot Interview Questions

Spring Boot vs. Spring MVC vs. Spring: How Do They Compare?

Spring Boot vs. Spring MVC vs. Spring: How Do They Compare?

In this article, you will receive overviews of Spring, Spring MVC, and Spring Boot, learn what problems they solve, and where they’re best applied. The most important thing that you will learn is that Spring, Spring MVC, and Spring Boot are not competing for the same space. They solve different problems and they solve them very well.

In this article, you will receive overviews of Spring, Spring MVC, and Spring Boot, learn what problems they solve, and where they’re best applied. The most important thing that you will learn is that Spring, Spring MVC, and Spring Boot are not competing for the same space. They solve different problems and they solve them very well.

Spring, Spring Boot, Spring MVC, there are springs everywhere! Let's walk through where and when you should apply each of these tools.

What Is the Core Problem That Spring Framework Solves?

Think long and hard. What’s the problem Spring Framework solves?

The most important feature of Spring Framework is Dependency Injection. At the core of all Spring Modules is Dependency Injection or IOC Inversion of Control.
Why is this important? Because, when DI or IOC is used properly, we can develop loosely coupled applications. And loosely coupled applications can be easily unit tested.

Let’s consider a simple example.

Example Without Dependency Injection

Consider the example below: WelcomeController depends on WelcomeService to get the welcome message. What is it doing to get an instance of WelcomeService?

WelcomeService service = new WelcomeService();

It’s creating an instance of it. And that means they are tightly coupled. For example: If I create a mock for WelcomeService in a unit test for WelcomeController, how do I make WelcomeController use the mock? Not easy!

@RestController
public class WelcomeController {

    private WelcomeService service = new WelcomeService();

    @RequestMapping("/welcome")
    public String welcome() {
        return service.retrieveWelcomeMessage();
    }
}

Same Example with Dependency Injection

The world looks much simpler with dependency injection. You let the Spring Framework do the hard work. We just use two simple annotations: @Component and @Autowired.

  • Using @Component, we tell Spring Framework: Hey there, this is a bean that you need to manage.
  • Using @Autowired, we tell Spring Framework: Hey find the correct match for this specific type and autowire it in.

In the example below, Spring framework would create a bean for WelcomeService and autowire it into WelcomeController.

In a unit test, I can ask the Spring framework to auto-wire the mock of WelcomeService into WelcomeController. (Spring Boot makes things easy to do this with @MockBean. But, that’s a different story altogether!)

@Component
public class WelcomeService {
    //Bla Bla Bla
}

@RestController
public class WelcomeController {

    @Autowired
    private WelcomeService service;

    @RequestMapping("/welcome")
    public String welcome() {
        return service.retrieveWelcomeMessage();
    }
}

What Else Does Spring Framework Solve?

Problem 1: Duplication/Plumbing Code

Does Spring Framework stop with Dependency Injection? No. It builds on the core concept of Dependency Injection with a number of Spring Modules

  • Spring JDBC
  • Spring MVC
  • Spring AOP
  • Spring ORM
  • Spring JMS
  • Spring Test

Consider Spring JMS and Spring JDBC for a moment.

Do these modules bring in any new functionality? No. We can do all this with J2EE or Java EE. So, what do these bring in? They bring in simple abstractions. The aim of these abstractions is to

  • Reduce Boilerplate Code/Reduce Duplication
  • Promote Decoupling/Increase Unit Testability

For example, you need much less code to use a JDBCTemplate or a JMSTemplate compared to a traditional JDBC or JMS.

Problem 2: Good Integration With Other Frameworks

The great thing about Spring Framework is that it does not try to solve problems that are already solved. All that it does is to provide a great integration with frameworks which provide great solutions.

  • Hibernate for ORM
  • iBatis for Object Mapping
  • JUnit and Mockito for Unit Testing
What Is the Core Problem That Spring MVC Framework Solves?

Spring MVC Framework provides decoupled way of developing web applications. With simple concepts like Dispatcher Servlet, ModelAndView and View Resolver, it makes it easy to develop web applications.## Why Do We Need Spring Boot?

Spring based applications have a lot of configuration.

When we use Spring MVC, we need to configure component scan, dispatcher servlet, a view resolver, web jars(for delivering static content) among other things.

  <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
  </bean>

  <mvc:resources mapping="/webjars/**" location="/webjars/"/>


The code snippet below shows the typical configuration of a dispatcher servlet in a web application.

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/todo-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


When we use Hibernate/JPA, we would need to configure a datasource, an entity manager factory, a transaction manager among a host of other things.

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="${db.driver}" />
        <property name="jdbcUrl" value="${db.url}" />
        <property name="user" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

    <jdbc:initialize-database data-source="dataSource">
        <jdbc:script location="classpath:config/schema.sql" />
        <jdbc:script location="classpath:config/data.sql" />
    </jdbc:initialize-database>

    <bean
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        id="entityManagerFactory">
        <property name="persistenceUnitName" value="hsql_pu" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>


Problem #1: Spring Boot Auto Configuration: Can We Think Different?

Spring Boot brings a new thought process around this.

Can we bring more intelligence into this? When a spring mvc jar is added into an application, can we auto configure some beans automatically?* How about auto-configuring a Data Source if Hibernate jar is on the classpath?

  • How about auto-configuring a Dispatcher Servlet if Spring MVC jar is on the classpath?

There would be provisions to override the default auto configuration.

Spring Boot looks at a) Frameworks available on the CLASSPATH b) Existing configuration for the application. Based on these, Spring Boot provides basic configuration needed to configure the application with these frameworks. This is called Auto Configuration.### Problem #2: Spring Boot Starter Projects: Built Around Well-Known Patterns

Let’s say we want to develop a web application.

First of all, we would need to identify the frameworks we want to use, which versions of frameworks to use and how to connect them together.

All web application have similar needs. Listed below are some of the dependencies we use in our Spring MVC Course. These include Spring MVC, Jackson Databind (for data binding), Hibernate-Validator (for server side validation using Java Validation API) and Log4j (for logging). When creating this course, we had to choose the compatible versions of all these frameworks.

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.2.2.RELEASE</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.2.Final</version>
</dependency>

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>


Here’s what the Spring Boot documentations says about starters.

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go.
Let’s consider an example starter: Spring Boot Starter Web.

If you want to develop a web application or an application to expose restful services, Spring Boot Start Web is the starter to pick. Let’s create a quick project with Spring Boot Starter Web using Spring Initializr.

Dependency for Spring Boot Starter Web

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>


The following screenshot shows the different dependencies that are added into our application

Dependencies can be classified into:

  • Spring: core, beans, context, aop
  • Web MVC: (Spring MVC)
  • Jackson: for JSON Binding
  • Validation: Hibernate Validator, Validation API
  • Embedded Servlet Container: Tomcat
  • Logging: logback, slf4j

Any typical web application would use all these dependencies. Spring Boot Starter Web comes pre-packaged with these. As a developer, I would not need to worry about either these dependencies or their compatible versions.

Spring Boot Starter Project Options

As we see from Spring Boot Starter Web, starter projects help us in quickly getting started with developing specific types of applications.

  • spring-boot-starter-web-services: SOAP Web Services
  • spring-boot-starter-web: Web and RESTful applications
  • spring-boot-starter-test: Unit testing and Integration Testing
  • spring-boot-starter-jdbc: Traditional JDBC
  • spring-boot-starter-hateoas: Add HATEOAS features to your services
  • spring-boot-starter-security: Authentication and Authorization using Spring Security
  • spring-boot-starter-data-jpa: Spring Data JPA with Hibernate
  • spring-boot-starter-cache: Enabling Spring Framework’s caching support
  • spring-boot-starter-data-rest: Expose Simple REST Services using Spring Data REST
Other Goals of Spring Boot

There are a few starters for technical stuff as well

  • spring-boot-starter-actuator: To use advanced features like monitoring and tracing to your application out of the box
  • spring-boot-starter-undertow, spring-boot-starter-jetty, spring-boot-starter-tomcat: To pick your specific choice of Embedded Servlet Container
  • spring-boot-starter-logging: For Logging using logback
  • spring-boot-starter-log4j2: Logging using Log4j2

Spring Boot aims to enable production ready applications in quick time.

  • Actuator: Enables Advanced Monitoring and Tracing of applications.
  • Embedded Server Integrations: Since the server is integrated into the application, I would need to have a separate application server installed on the server.
  • Default Error Handling