How to Show and Hide Div On Button Toggle in React

Last Updated on by in React JS

React, a JavaScript library for building user interfaces, provides a flexible environment for creating dynamic web applications. One common task in React development involves toggling the visibility of elements, such as divs, based on user actions.

In this short and sweet guide, we will walk you through a bit-by-bit process on how to show and hide a div on button click in the React application using React Hooks (useState, useEffect) and the Bootstrap CSS framework.

There are a plethora of React functionalities that we have discussed in the past, however, this tutorial focuses on a tiny but important functionality to show and hide specific sections on a web page.

We’ll create a simple app with a single component, three buttons, HTML sections, or divs, and implement a feature that shows the single section while others remain closed on a button click.

Create React Project

We assume you have already installed node, npm in your system, use the following command to create a new react app.

npx create-react-app react-features

You can use the given command to enter into the project.

cd react-features

Add Bootstrap Module

The bootstrap module is completely optional; the primary purpose of using bootstrap is to reduce the UI development time drastically.

Here is the command which will install the module in your react app.

npm i react-bootstrap bootstrap --legacy-peer-deps

Build Component File

It is ideal approach to keep the components in specific file, make sure to create the /components, folder with /Home.js file inside of it.

import React from 'react'

function Home() {
  return (
    <div>Home</div>
  )
}

export default Home

Show and Hide Div

The useState hook refers to the id of the current button and div, which we need to show currently.

Create an event handler and bind it to the button element with the onClick event handler.

It gives us access to the current element’s id when clicked. To show and hide the div, we are adding the current state in conjunction with the button and div id.

Add the code into the Home.js file.

import React, { useState, useEffect } from 'react'

function Home() {
  const [isActive, setIsActive] = useState({
    id: 'divOne',
  })

  useEffect(() => {
    console.log(isActive)
  }, [isActive])

  const hideShowDiv = (e) => {
    setIsActive({
      id: e.target.id,
    })
  }

  return (
    <div className="row">
      <h2 className="mb-5 text-center">
        React Hide and Show Single Div Example
      </h2>

      <div className="col-4">
        <div className="d-grid mb-4">
          <button
            id="divOne"
            onClick={(e) => {
              hideShowDiv(e)
            }}
            className="btn btn-danger"
          >
            Show
          </button>
        </div>
        <div className={isActive.id === 'divOne' ? `divOne` : 'divOne d-none'}>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
        </div>
      </div>

      <div className="col-4">
        <div className="d-grid mb-4">
          <button
            id="divTwo"
            onClick={(e) => {
              hideShowDiv(e)
            }}
            className="btn btn-success"
          >
            Show
          </button>
        </div>

        <div className={isActive.id === 'divTwo' ? `divTwo` : 'divTwo d-none'}>
          <p>
            Pellentesque molestie ipsum nisl, vel convallis nisl scelerisque et.
          </p>
        </div>
      </div>

      <div className="col-4">
        <div className="d-grid mb-4">
          <button
            id="divThree"
            onClick={(e) => {
              hideShowDiv(e)
            }}
            className="btn btn-primary"
          >
            Show
          </button>
        </div>
        <div
          className={isActive.id === 'divThree' ? `divThree` : 'divTwo d-none'}
        >
          <p>
            Sed suscipit, nunc et malesuada imperdiet, massa justo sollicitudin
            ligula.
          </p>
        </div>
      </div>
    </div>
  )
}

export default Home

Update Global Component

App component is being used to serve the react app, therefore we need to register the Home component into the App.js file.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import './App.css'
import Home from './components/Home'

export default function App() {
  return (
    <div className="container mt-5">
      <Home />
    </div>
  )
}

Run React Server

Head over to the terminal, add the given command on the console then hit enter.

npm start

Your app will be served on the given url.

http://localhost:3000

React Js Bootstrap Show and Hide Single Div Tutorial

Summary

In this short post, we have revealed how to show and hide div within the functional component in a React js application.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.