Open Dropdown On Button Click React JS

Open Dropdown On Button Click React JS

Sometimes there is a need of opening a drop down on some event’s like onpage load, or on some button click in React App. And to achieve this in React App is a very easy task. Here in this post, we will be learning to open drop down on button click.

Here we will have a React App and And bootStrap added in it. As we will be using bootstrap dropdown.

Some like this we are going to achive.

Open Dropdown On Button Click React JS

Adding BootStrap to React App

In our React App we will need to add bootstrap css, bootstrap js and jquery. We will add this in index.html which resides under public folder in react app.

<link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
    />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

Adding Bootstrap DropDown element in App.js in react app

BootStrap DropDown Code. That we will add in our App.js

 <div className="col col-sm-6">
          <div className={this.state.openDropwDown}>
            <button
              className="btn btn-primary dropdown-toggle"
              type="button"
              data-toggle="dropdown"
              //aria-expanded="true"
            >
              Dropdown Example
              <span className="caret"></span>
            </button>
            <ul className="dropdown-menu">
              <li>
                <a href="#">HTML</a>
              </li>
              <li>
                <a href="#">CSS</a>
              </li>
              <li>
                <a href="#">JavaScript</a>
              </li>
            </ul>
          </div>
        </div>

You might have noticed that at line 2 we are updating the class property by fetching it from the component state.

<div className={this.state.openDropwDown}>

Adding function to toggle dropdown item opening and closing in React App

The bootstrap dropdown has two classes ( dropdown and open) responsible for displaying dropdown.

dropdown class: Is the mandatory class for drop-down element. That’s why this class will be always there with the dropdown element

Open class: open class will be added when we want to open the bootstrap and will be removed when we want to close the dropdown.

To achieve above point we will write one function which will be responsible for updating the react’s state value by class “dropdown” when we need to close the dropdown list and to “dropdown open” when we need to display dropdown list.

Below is the function we discussed above (App.js).

openDropwDown = () => {
    let value = "dropdown open";
    if (this.state.openDropwDown === "dropdown open") {
      value = "dropdown";
    }
    console.log(value);
    this.setState({ openDropwDown: value });
  };

Here is how our’s React State looks like

 state = {
    openDropwDown: "dropdown",
  };

Now, After adding function let’s call it on button click

Adding Button to toggle dropdown list.

Button code(app.js).

        <div className="col col-sm-6 text-center">
          <div className="btn btn-primary" 
           onClick= {this.openDropwDown}>
            {" "}
            Click To Open DropDown
          </div>
        </div>

Here at line 3, we are calling openDropwDown function that we create above.This will make sure that dropdown items are visible and closed at button clicked.

Now, Run your react app using command npm start

After our app start we will be seeing something like this.

Open Dropdown On Button Click React JS
Open Dropdown On Button Click React JS

Complete Code

Below is complete code

Index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
    />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

App.js

import React, { Component } from "react";
import logo from "./logo.svg";
class App extends Component {
  state = {
    openDropwDown: "dropdown",
  };
  render() {
    return (
      <div className="row">
        <div className="col col-sm-6 text-center">
          <div className="btn btn-primary" onClick={this.openDropwDown}>
            {" "}
            Click To Open DropDown
          </div>
        </div>
        <div className="col col-sm-6">
          <div className={this.state.openDropwDown}>
            <button
              className="btn btn-primary dropdown-toggle"
              type="button"
              data-toggle="dropdown"
              //aria-expanded="true"
            >
              Dropdown Example
              <span className="caret"></span>
            </button>
            <ul className="dropdown-menu">
              <li>
                <a href="#">HTML</a>
              </li>
              <li>
                <a href="#">CSS</a>
              </li>
              <li>
                <a href="#">JavaScript</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    );
  }
  openDropwDown = () => {
    let value = "dropdown open";
    if (this.state.openDropwDown === "dropdown open") {
      value = "dropdown";
    }
    console.log(value);
    this.setState({ openDropwDown: value });
  };
}

export default App;

Link to Git

You can find complete code at git

Conclusion

Here in this section of the post, we have seen the way of dynamically opening the dropdown list on button click in react js App. And also learned how to add Bootstrap CSS and Bootstrap JS to our React App

Thanks, Note

Thanks for spending you valuable time on this post hope this post was use full to you and you learned something new today. If you like our post please share our post.

You might check out this post to that illustrate, How To Open Dialog Box In React Js

Durgesh Kumar

He is the Founder of TechiJournal.com. And have 4+ years of experience as full-stack Java developer. He worked with many reputed product companies and would like to share his experience and knowledge through this blog. He works very hard to provide you with quality content. But as no one is perfect, If you feel that some improvement can be made then feel free to add it in the comment section. We look forward to it.

This Post Has 2 Comments

Leave a Reply