Categories
React Projects

Create an Accordion Component with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create an accordion component with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app accordion

with NPM to create our React project.

Create the Accordion

To create the accordion, we write:

import React, { useState } from "react";

export default function App() {
  const [contents, setContents] = useState(
    Array(10)
      .fill()
      .map((_, i) => {
        return {
          title: `title ${i}`,
          description: `description ${i}`,
          expanded: false
        };
      })
  );

  return (
    <div className="App">
      <style>
        {`
          .title {
            cursor: pointer;
            display: flex;
            justify-content: space-between;
          }

          .title,
          .description {
            border: 1px solid black;
            padding: 5px;
          }
        `}
      </style>
      {contents.map((c, i) => {
        return (
          <div key={c.title}>
            <div
              className="title"
              onClick={() => {
                const c = [...contents];
                c[i].expanded = !c[i].expanded;
                setContents(c);
              }}
            >
              <div>
                <b>{c.title}</b>
              </div>
              <div>
                {c.expanded ? <span>&#x2191;</span> : <span>&#x2193;</span>}
              </div>
            </div>
            {c.expanded && <div className="description">{c.description}</div>}
          </div>
        );
      })}
    </div>
  );
}

We have the contents array with the accordion contents.

Next, we add the style tag to add the styles for the accordion title and content.

Then we render the contents array into an accordion with the title div.

The onClick prop is set to a function that copies the contents array.

Then we toggle the expanded property of the contents entry with index i .

Then we call setContents with c to update the contents array.

Inside the wrapper, we show the c.title value.

And below that, we add the code for showing the arrows to the right of c.title according to the value of c.expanded .

&#x2191; is the up arrow, and &#x2193; is the down arrow.

And below that, we show the description div when c.expanded is true .

Conclusion

We can add an accordion with Reactr and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *