Site icon Coding is Love

How to create a collapsible in React easily

Collapsible that reveals or hides contest with an animation is a very common pattern used in web. Let’s see how to create a collapsible that opens on click easily in React

Collapsible using auto-animate

AutoAnimate is a zero-config, drop-in animation utility that adds smooth transitions to your web app. You can use it with React, Solid, Vue, Svelte, or any other JavaScript application.

In this blog post, we’ll look at how to use it in ReactJs

Installation

Install using your package manager of choice to add @formkit/auto-animate to your project:

Yarn

yarn add @formkit/auto-animate

NPM

npm install @formkit/auto-animate

Usage

Using auto-animate to create a collapsible or accordion is very easy. All you need to do is use the useAutoAnimate hook and pass the return value to any list container. Once this is done, any child element that is removed from the div will be auto-animated!

Here’s some example code:

import { useAutoAnimate } from '@formkit/auto-animate/react'

function MyList () {
  const [animationParent] = useAutoAnimate()
  return (
    <div ref={animationParent}>
      {/* 🪄 Magic animations for your child elements */}
    </div>
  )
}

Working demo

I’ve created a working demo in code sandbox to show how it works live. Here’s the code and the demo embedded below.

import "./styles.css";
import { useState, useRef, useEffect } from "react";
import autoAnimate from "@formkit/auto-animate";

export default function App() {
  const [show, setShow] = useState(false);
  const parent = useRef(null);

  useEffect(() => {
    parent.current && autoAnimate(parent.current);
  }, [parent]);

  const reveal = () => setShow(!show);
  return (
    <div className="container" ref={parent} onClick={reveal}>
      <strong className="dropdown-label">Click me to open!</strong>
      {show && (
        <p className="dropdown-content">
          Sea of Tranquility a mote of dust suspended in a sunbeam hundreds of
          thousands concept of the number one realm of the galaxies radio
          telescope. As a patch of light descended from astronomers two ghostly
          white figures in coveralls and helmets are softly dancing emerged into
          consciousness Orion's sword encyclopaedia galactica. Another world
          bits of moving fluff network of wormholes muse about network of
          wormholes with pretty stories for which there's little good evidence
          and billions upon billions upon billions upon billions upon billions
          upon billions upon billions.
        </p>
      )}
    </div>
  );
}

Also, Read How to animate list reordering with React easily

Exit mobile version