Open In App

Accordion Template using ReactJS and Tailwind

Last Updated : 23 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

An Accordion is a component which can show data in form of collapsing and expanding. This is very useful in places where we have less amount of space available and only necessary information is to be provided to the end user. It provides ease of access in displaying data as user is shown only the required data and other components are hidden.

The final feature will look like:

Accordion Template

Basic features in an accordion are:

  • Title: This contains the information which is always displayed to the user
  • Content/Data: This is the information which the user selects to view
  • Collapse/Expand: A feature using which user can collapse and expand selected information
  • Transition: Smooth transitions during expanding/collapsing which enhances user experience

Prerequisites:

Approach:

  • Set up a basic react project and install the required dependencies.
  • Create the basic layout consisting of a Navbar and Welcome slide.
  • Style the components using Tailwind.
  • Pass the data dynamically in the components and render it on the screen.

Step to create the project

Step 1: Set up the project using the command

 npx create-react-app <<Project_Name>>

Step 2: Navigate to the folder using the command

cd <<Project_Name>>

Step 3: Install the required dependencies using the command

npm install -D tailwindcss

Step 4: Create the tailwind config file using the command

npx tailwindcss init

Step 5: Rewrite the tailwind.config.js file as folllows

/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

Step 6: Create a folder called components in src directory and add the file Accordion.js and Navbar.js

Project Structure:

Project Structure

The updated dependencies in package.json will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
"devDependencies": {
"tailwindcss": "^3.3.3"
}

Example: Add the following code in respective files:

Javascript




// App.js
  
import logo from './logo.svg';
import './App.css';
import Accordion from './components/Accordion';
import { useState } from 'react';
import Navbar from './components/Navbar';
  
const App = () => {
    const [accordions, setAccordion] = useState([
        {
            key: 1,
            title: 'What is GeeksforGeeks?',
            data: `GeeksforGeeks is a one stop solution 
                      for all computer science students.`,
            isOpen: false
        },
        {
            key: 2,
            title: 'What GeeksforGeeks offer us?',
            data: `GeeksforGeeks offers Free Tutorials, 
                      Millions of Articles, Live, Online and 
                      Classroom Courses,Frequent Coding Competitions, 
                      Webinars by Industry Experts, Internship 
                      opportunities and Job Opportunities.`,
            isOpen: false
        },
        {
            key: 3,
            title: 'Which is the best portal to study Computer Science?',
            data: `GeeksforGeeks is the best Computer Science portal 
                      for geeks. It contains well written, well thought 
                      and well explained computer science and programming 
                      articles.`,
            isOpen: false
        },
    ]);
  
    const toggleAccordion = (accordionkey) => {
        const updatedAccordions = accordions.map((accord) => {
            if (accord.key === accordionkey) {
                return { ...accord, isOpen: !accord.isOpen };
            } else {
                return { ...accord, isOpen: false };
            }
        });
  
        setAccordion(updatedAccordions);
    };
  
    return (
        <div>
            <Navbar/>
            <div className="p-2 m-8">
                <h2 className='text-2xl mb-2 mx-auto text-green-800'>Accordion Using React and Tailwind</h2>
                {accordions.map((accordion) => (
                    <Accordion
                        key={accordion.key}
                        title={accordion.title}
                        data={accordion.data}
                        isOpen={accordion.isOpen}
                        toggleAccordion={() => toggleAccordion(accordion.key)}
                    />
                ))}
            </div>
        </div>
    );
};
  
export default App;


Javascript




// Accordion.js
  
export default function Accordion(props) {
    return (
        <div className="border rounded-md mb-1">
            <button
                className="w-full p-4 text-left bg-gray-200 
                           hover:bg-gray-300 transition duration-300"
                onClick={props.toggleAccordion}
            >
                {props.title}
                <span className={`float-right transform ${props.isOpen ? 
                                 'rotate-180' : 'rotate-0'
                                 transition-transform duration-300`}>
                    &#9660;
                </span>
            </button>
            {props.isOpen && (
                <div className="p-4 bg-white">
                    {props.data}
                </div>
            )}
        </div>
    );
};


Javascript




// Navbar.js
  
export default function Navbar() {
    return (
        <div>
            <nav classNameName="bg-white fixed w-full
                                z-20 top-0 left-0
                                border-b border-gray-200">
                <div className="flex flex-wrap items-center
                                justify-between mx-auto p-4">
                    <a href="https://geeksforgeeks.org/"
                    className="flex items-center">
                        <img src=
                            className="mr-2"
                            alt="GFG Logo" />
                        <span className="self-center text-2xl font-semibold ">
                            GeeksforGeeks
                        </span>
                    </a>
                    <div className="items-center justify-between hidden
                                    w-full md:flex md:w-auto md:order-1"
                        id="navbar-sticky">
                        <ul className="flex flex-col p-4
                                    md:p-0 mt-4 font-medium
                                    border border-gray-100 rounded-lg
                                    bg-gray-50 md:flex-row md:space-x-8
                                    md:mt-0 md:border-0 md:bg-white">
                            <li>
                                <a href="#"
                                className="block py-2 pl-3
                                            pr-4 text-white bg-blue-700
                                            rounded md:bg-transparent
                                            md:text-blue-700 md:p-0">
                                    Home
                                </a>
                            </li>
                            <li>
                                <a href="#"
                                className="block py-2 pl-3
                                            pr-4 text-gray-900 rounded
                                            hover:bg-gray-100
                                            md:hover:bg-transparent
                                            md:hover:text-blue-700 md:p-0">
                                    Posts
                                </a>
                            </li>
                            <li>
                                <a href="#"
                                className="block py-2 pl-3
                                            pr-4 text-gray-900 rounded
                                            hover:bg-gray-100
                                            md:hover:bg-transparent
                                            md:hover:text-blue-700 md:p-0">
                                    About us
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </div>
    )
}


CSS




/* Index.css */
  
@tailwind base;
@tailwind components;
@tailwind utilities;
  
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
  
code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;
}


Steps to run the application:

Step 1: Type the following command in terminal of project directory

npm start

Step 2: Open the following link in browser

http://localhost:3000/

Output:

Accordion Template



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads