DEV Community

Cover image for Collapsible Item in ReactJS using Reactstrap
Shubham Tiwari
Shubham Tiwari

Posted on

Collapsible Item in ReactJS using Reactstrap

Hello Everyone Today i am going to show you how you can create a collapse effect in react using reactstrap.It is the easiest way to create this effect and you are going to love it.

Lets get started...

What is ReactStrap?
Reactstrap is a component library for React. It provides inbuilt Bootstrap components that make it easy to create UI with self-contained components that provide flexibility and inbuilt validations. Reactstrap is easy to use and supports Bootstrap 4.

Installation -

npm install --save reactstrap
Enter fullscreen mode Exit fullscreen mode

A simple collapsible navbar -

import React,{useState} from 'react'
import './App.css';
import { Button, Collapse } from 'reactstrap';


function App() {

    const [collapse, setCollapse] = useState(true);
    const toggle = () => setCollapse(!Collape);
    return (

            <div className="main-navbar-box">
                    <Button color="primary" onClick={toggle} style={{ marginBottom: '1rem' }}>
                       <i class="fa fa-bars" aria-hidden="true" onClick={toggle}></i>
                    </Button>

                     <Collapse isOpen={collapse}>

                            <nav>
                                <ul>
                                    <li>Home</li>
                                    <li>Menu</li>
                                    <li>About</li>
                                    <li>Contact</li>
                                </ul>
                            </nav>

                    </Collapse>
            </div>

)
}
Enter fullscreen mode Exit fullscreen mode

Explaination -

  1. First we have imported the Button and Collapse component from react strap.
  2. Then we created a state using useState hook and give it a value of false(means closed navbar)
  3. Then we created an arrow function which change the state of the collapse component to true which creates a collapse effect
  4. Then we created a button using Button component and inside it we have created onClick event handler and provide the variable which is assigned to the arrow function we have created.
  5. Then we created our navbar inside the Collapse component and inside Collapse tag we have an attribute called isOpen which have the collapse value and when the value of collapse is changed using the button component then the state of Collapse also changes.(if true then false and if false then true).

Output -

Image description
Image description
NOTE - I didn't give the css code you can style the navbar as you like.

THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE SUGGESTION THEN MENTION IT IN THE COMMENT SECTION.

Top comments (0)