DEV Community

Vijaya Kumar
Vijaya Kumar

Posted on

Build a React accordion widget in 2 minutes

This is my first post in dev community. Today, I want to share build simple plain accordion using react. This section is really important section of an app or a website, since you have an opportunity to have important questions and answers about your services/product or even your industry and rank better organically in Google.

I hope I'm able to help anyone who wants or needs to build an accordion section for their website or their app.

I'm leaving the URL of the code and styles at the end of the article and also a working demo if you want to check it out.

We will use React useState hooks. Which is enough to accomplish the accordion implementation.

Simple Click event,


  const [active, setActive] = useState(-1);
  const accordian = [
    {
      title: 'Accordion 1',
      paras: [
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.',
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.',
      ],
    },
    {
      title: 'Accordion 2',
      paras: [
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.',
      ],
    },
    {
      title: 'Accordion 3',
      paras: [
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.',
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.',
      ],
    },
  ];

  const handleClick = (index) => {
    if (index === active) setActive(-1);
    else setActive(index);
  };
Enter fullscreen mode Exit fullscreen mode

Then we have the DOM rendering part of the code using an onClick and ternary operators, like so

<ul className="accordian">
        {accordian.map((item, index) => {
          return (
            <li
              key={index}
              onClick={() => handleClick(index)}
              className={index === active ? 'active' : ''}
            >
              <div className="accordian-title">{item.title}</div>
              <div className="accordian-content">
                {item.paras.map((para) => {
                  return <p>{para}</p>;
                })}
              </div>
            </li>
          );
        })}
</ul>
Enter fullscreen mode Exit fullscreen mode

Alt Text

demo link: https://stackblitz.com/edit/react-u5w7ex

Top comments (0)