Categories
React

Animate with the react-spring Library — useChain and Spring Component

With the react-spring library, we can render animations in our React app easily.

In this article, we’ll take a look at how to get started with react-spring.

useChain

The useChain hook lets us render one transition after the other.

For example, we can write:

import React, { useRef, useState } from "react";
import {
  useTransition,
  animated,
  useChain,
  useSpring,
  useTrail
} from "react-spring";

export default function App() {
  const [on, toggle] = useState(false);

  const springRef = useRef();
  const spring = useSpring({
    ref: springRef,
    from: { opacity: 0.5 },
    to: { opacity: on ? 1 : 0.5 },
    config: { tension: 250 }
  });

  const trailRef = useRef();
  const trail = useTrail(5, {
    ref: trailRef,
    from: { fontSize: "10px" },
    to: { fontSize: on ? "35px" : "10px" }
  });

  useChain(on ? [springRef, trailRef] : [trailRef, springRef]);

  return (
    <div>
      {trail.map((animation, index) => (
        <animated.div style={{ ...animation, ...spring }} key={index}>
          Hello World
        </animated.div>
      ))}

      <button onClick={() => toggle(!on)}>toggle</button>
    </div>
  );
}

to animate the toggling of the size of the ‘Hello World’ text.

We create the on state with the toggle function to toggle the on state.

Then we create a ref with the useRef hook and create a transition with the useSpring hook.

We set the ref property to the springRef so we can use that in the useChain hook.

Likewise, we use the useTrail to create the 2nd transition.

Then we use th useChain hook to create the 2 animations combined together.

Their order depends on the value of the on state.

Then we render the Hello World text by calling the trail.map method to apply the styles for each stage of the animation.

Now when we click ‘toggle’, we see the Hello World text size change.

Render Props API

The react-spring library comes with a render props API.

To use this to create animations, we use the Spring component.

For example, we can write:

import React from "react";
import { Spring } from "react-spring/renderprops";

export default function App() {
  return (
    <div>
      <Spring from={{ opacity: 0 }} to={{ opacity: 1 }}>
        {(props) => <div style={props}>hello</div>}
      </Spring>
    </div>
  );
}

to add the Spring component.

We set the from prop to add the styles to apply at the start of the animation.

And we add the to prop to add the styles to apply at the end of the animation.

And in the render prop, we pass in a function with the content that we want to render.

The props parameter has the styles that are applied at each stage of the animation, so we pass that into the style prop to apply them.

Also, we can animate numbers by writing:

import React from "react";
import { Spring } from "react-spring/renderprops";

export default function App() {
  return (
    <div>
      <Spring from={{ number: 0 }} to={{ number: 1 }}>
        {(props) => <div>{props.number}</div>}
      </Spring>
    </div>
  );
}

We set the number to display at the beginning and the end of the animation with the from and to props respectively.

Then we the number animate from 0 to 1.

Conclusion

We can use the useChain hook to chain animations.

And we can use the Spring component to render animations.

Categories
React

Animate with the react-spring Library — useTransition Hook

With the react-spring library, we can render animations in our React app easily.

In this article, we’ll take a look at how to get started with react-spring.

useTransition

We can use the useTransition hook to add transitions to our React components.

For example, we can write:

import React, { useState } from "react";
import { useTransition, animated } from "react-spring";

const arr = [
  { text: 1, key: 1 },
  { text: 2, key: 2 },
  { text: 3, key: 3 }
];

export default function App() {
  const [items] = useState(arr);
  const transitions = useTransition(items, (item) => item.key, {
    from: { transform: "translate3d(0,-40px,0)" },
    enter: { transform: "translate3d(0,0px,0)" },
    leave: { transform: "translate3d(0,-40px,0)" }
  });
  return transitions.map(({ item, props, key }) => (
    <animated.div key={key} style={props}>
      {item.text}
    </animated.div>
  ));
}

to animate the rendering of the arr array with the useTransition hook.

We create the items state from the useState hook.

Then we pass that into the useTransition hook as its first argument.

In the 2nd argument, we pass in a function to return the key property of each item, which is its unique ID.

It’s used by React to keep track of the items.

The 3rd argument has an object with the styles that we want to render before the animation with the from property.

The enter property has the styles to display when the item enters.

And the leave property has the styles to display when the item leaves.

Now we should see the numbers move down to the screen.

We can also use the useTransition hook to toggle between components.

For example, we can write:

import React, { useState } from "react";
import { useTransition, animated } from "react-spring";

export default function App() {
  const [toggle, set] = useState(false);
  const transitions = useTransition(toggle, null, {
    from: { position: "absolute", opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 }
  });
  return (
    <>
      <button onClick={() => set(!toggle)}>toggle</button>
      {transitions.map(({ item, key, props }) =>
        item ? (
          <animated.div style={props} key={key}>
            <span role="img" aria-label="smile">
              ?
            </span>
          </animated.div>
        ) : (
          <animated.div style={props} key={key}>
            <span role="img" aria-label="smile">
              ?
            </span>
          </animated.div>
        )
      )}
    </>
  );
}

We have the toggle state, which is toggled with the button.

Then we call the useTransition hook to apply the styles by passing in the toggle state as the first argument.

The 3rd argument has the styles we want to apply when we animate.

When item toggles between truthy and falsy, then the corresp[onding emoji will display since we call transitions.map to map the transitions and.

item has the value that toggle has.

We can also use it to render things that are displayed when a condition is true .

For instance, we can write:

import React, { useState } from "react";
import { useTransition, animated } from "react-spring";

export default function App() {
  const [show, set] = useState(false);
  const transitions = useTransition(show, null, {
    from: { position: "absolute", opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 }
  });
  return (
    <>
      <button onClick={() => set(!show)}>toggle</button>
      {transitions.map(
        ({ item, key, props }) =>
          item && (
            <animated.div key={key} style={props}>
              <span role="img" aria-label="smile">
                ✌️
              </span>
            </animated.div>
          )
      )}
    </>
  );
}

Then when item is true , which is true when show is true , the emoji is displayed.

Conclusion

We can add transitions to our React components easily with the useTransition hook.

Categories
Vue

Vue 3 — Props

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at how to use props with Vue 3.

Props

Components can take props so that we can pass data from the parent component to it.

We can add props by defining the as an array of strings.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <blog-post title="hello world"></blog-post>
    </div>
    <script>
      const app = Vue.createApp({}); 
      app.component("blog-post", {
        props: ["title"],
        template: `<h1>{{title}}</h1>`
      }); 
      app.mount("#app");
    </script>
  </body>
</html>

We created a blog-post component with the props property to define which props we accept.

The array has the names of the props as strings.

Then we can pass in the props as we did with title .

Props are just attributes that can have any value we want.

Prop Types

To make passing props easier, we can check the data type of the prop.

This way, we’ll get an error if we pass in some value that we don’t expect.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <blog-post title="hello world"></blog-post>
    </div>
    <script>
      const app = Vue.createApp({}); 
      app.component("blog-post", {
        props: {
          title: String
        },
        template: `<h1>{{title}}</h1>`
      }); 
      app.mount("#app");
    </script>
  </body>
</html>

to set the title prop type to a string.

We can pass in any other constructor to set the valid type of a prop, like:

props: {
  title: String,
  likes: Number,
  date: Date,
  commentIds: Array,
  author: Object,
  callback: Function,
  contactsPromise: Promise
}

This also serves as good documentation of ur component.

Passing Static or Dynamic Props

Static props can be passed in with v-bind .

We did with the title prop in the previous example.

We have:

<blog-post title="hello world"></blog-post>

which has the title prop and it’s a static string.

If we want to pass in anything else, then we need to use v-bind or : for short.

For example, we can write:

<blog-post :title="post.title"></blog-post>

to pass in the title property of the post object.

We can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <blog-post v-for="post of posts" :title="post.title"></blog-post>
    </div>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            posts: [
              { title: "hello world", author: "james" },
              { title: "good news", author: "james" },
              { title: "bad news", author: "james" }
            ]
          };
        }
      }); 

      app.component("blog-post", {
        props: {
          title: String
        },
        template: `<h1>{{title}}</h1>`
      }); 
      app.mount("#app");
    </script>
  </body>
</html>

to pass the title property of post to the title prop.

We can also pass in an expression.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <blog-post
        v-for="post of posts"
        :title="`${post.title} by ${post.author}`"
      ></blog-post>
    </div>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            posts: [
              { title: "hello world", author: "james" },
              { title: "good news", author: "mary" },
              { title: "bad news", author: "jane" }
            ]
          };
        }
      }); 

      app.component("blog-post", {
        props: {
          title: String
        },
        template: `<h1>{{title}}</h1>`
      }); 
      app.mount("#app");
    </script>
  </body>
</html>

We created a string from the title and author properties and pass that in as the title prop’s value.

Conclusion

We can register props to let us pass values to child components.

Also, we can validate the data type with constructors as the values of the prop property.

Categories
React

Animate with the react-spring Library — useSprings and useTrail Hooks

With the react-spring library, we can render animations in our React app easily.

In this article, we’ll take a look at how to get started with react-spring.

useSprings

The useSprings hook lets us create multiple springs each with its own config.

For example, we can write:

import React from "react";
import { animated, useSprings } from "react-spring";

const items = [
  { text: "foo", opacity: 0.3, id: 1 },
  { text: "bar", opacity: 0.6, id: 2 },
  { text: "baz", opacity: 0.9, id: 3 }
];

export default function App() {
  const springs = useSprings(
    items.length,
    items.map((item) => ({ opacity: item.opacity, from: { opacity: 0 } }))
  );

  return (
    <>
      {springs.map((props, i) => (
        <animated.div style={props} key={i}>
          {items[i].text}
        </animated.div>
      ))}
    </>
  );
}

to create the animation styles for each item with the useSprings hook.

The first argument is the number of style objects to create.

The 2nd argument is an array with the styles we want to apply.

Then in the JSX, we apply the styles by passing in the props to the style prop.

We can also control our animation with the set and stop functions.

For example, we can write:

import React from "react";
import { animated, useSprings } from "react-spring";

const items = [
  { text: "foo", opacity: 0.3, id: 1 },
  { text: "bar", opacity: 0.6, id: 2 },
  { text: "baz", opacity: 0.9, id: 3 }
];

export default function App() {
  const [springs, set, stop] = useSprings(items.length, (index) => ({
    opacity: items[index].opacity,
    from: { opacity: 0 }
  }));

  return (
    <>
      <button onClick={() => set((index) => ({ opacity: 1 }))}>start</button>
      <button onClick={() => stop()}>stop</button>
      {springs.map((props, i) => (
        <animated.div style={props} key={i}>
          {items[i].text}
        </animated.div>
      ))}
    </>
  );
}

We have the same items array.

And we use the useSpring hook with a function as the 2nd argument instead of an array of styles.

Calling it with a function as the 2nd argument will give us the set and stop functions in addition to springs ,

The set function lets us run the animation with the given style.

And the stop function lets us stop the animation.

Then we display the animated divs the same way.

useTrail

The useTrail lets us create multiple springs with a single config.

For example, we can write:

import React from "react";
import { animated, useTrail } from "react-spring";

const items = [
  { text: "foo", id: 1 },
  { text: "bar", id: 2 },
  { text: "baz", id: 3 }
];

export default function App() {
  const trail = useTrail(items.length, { opacity: 1, from: { opacity: 0 } });

  return (
    <>
      {trail.map((props, i) => (
        <animated.div style={props} key={i}>
          {items[i].text}
        </animated.div>
      ))}
    </>
  );
}

The first argument is the number of animation style objects to create.

And the 2nd argument is the animation style to create.

Then we can apply them as we do with the useSprings hook.

Conclusion

We can create animations for a group of components with the useSprings and useTrail hooks.

Categories
React

Animate with the react-spring Library — useSpring Hook

With the react-spring library, we can render animations in our React app easily.

In this article, we’ll take a look at how to get started with react-spring.

useSpring

We can use the useSpring hook to add our animation.

For example, we can write:

import React, { useEffect, useState } from "react";
import { useSpring, animated } from "react-spring";

export default function App() {
  const [props, set, stop] = useSpring(() => ({ opacity: 1 }));
  const [toggle, setToggle] = useState();

  useEffect(() => {
    set({ opacity: toggle ? 1 : 0 });
  }, [toggle]);

  return (
    <>
      <button onClick={() => setToggle(!toggle)}>start</button>
      <button onClick={() => stop()}>stop</button>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

We pass in callback into the useSpring hook to create our animation.

We also have the toggle state to let us toggle the opacity with the set function.

So when we click start, we’ll see the fading of the text toggled.

And we have the stop function to stop the animation.

We can also use the useSpring by passing in an object.

For example, we can write:

import React from "react";
import { useSpring, animated } from "react-spring";

export default function App() {
  const props = useSpring({
    from: { opacity: 0 },
    to: { opacity: 1, color: "red" }
  });

  return (
    <>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

We animate from the styles with the from property to the styles in the to property.

We can shorten this to:

import React from "react";
import { useSpring, animated } from "react-spring";

export default function App() {
  const props = useSpring({
    from: { opacity: 0 },
    opacity: 1,
    color: "red"
  });

  return (
    <>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

Async Chains and Scripts

We can animate asynchronously with the next function.

For instance, we can write:

import React from "react";
import { useSpring, animated } from "react-spring";

export default function App() {
  const props = useSpring({
    to: async (next, cancel) => {
      await next({ opacity: 1, color: "#ffaaee" });
      await next({ opacity: 0, color: "rgb(14,26,19)" });
    },
    from: { opacity: 0, color: "red" }
  });

  return (
    <>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

The to method is an async function that has the next and cancel functions as parameters.

next lets us set the styles we want to apply in our animation.

And cancel lets us cancel the animation.

from is still an object with the initial styles of our div.

Also, we can create the to property with an array by writing:

import React from "react";
import { useSpring, animated } from "react-spring";

export default function App() {
  const props = useSpring({
    to: [
      { opacity: 1, color: "#ffaaee" },
      { opacity: 0, color: "rgb(14,26,19)" }
    ],
    from: { opacity: 0, color: "red" }
  });

  return (
    <>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

The array has objects with the styles we want to apply.

Conclusion

The useSpring hook lets us create animations easy for a single element.