Question:
How can I implement a toggle functionality in ReactJS?

This function is to implement a toggle functionality in ReactJS where clicking a function reveals a menu, and clicking outside the menu hides it.


To toggle, first use the useRef hook to create a reference to the dropdown div. After that use the useEffect hook to add an event listener for clicks outside the dropdown. On click of outside the dropdown, it checks if the clicked element is inside the dropdown using the contains method. If not, it closes the dropdown.

The handleToggle toggles the dropdown's visibility when the button is clicked.


Here's the implementation:

import React, { useState, useEffect, useRef } from "react";


function App() {

  const [isOpen, setIsOpen] = useState(false);

  const dropdownRef = useRef(null);


  useEffect(() => {

    const handleClickOutside = (event) => {

      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {

        setIsOpen(false);

      }

    };


    // Add event listener to handle clicks outside the dropdown

    document.addEventListener("mousedown", handleClickOutside);


    // Clean up the event listener on component unmount

    return () => {

      document.removeEventListener("mousedown", handleClickOutside);

    };

  }, []);


  const handleToggle = () => {

    setIsOpen((prev) => !prev);

  };


  return (

    <div ref={dropdownRef} className="dropdown">

      <button onClick={handleToggle}>Toggle Dropdown</button>

      {isOpen && (

        <div className="dropdown-content">

          {/* Dropdown content goes here */}

          <p>Dropdown content goes here</p>

        </div>

      )}

    </div>

  );

}


export default App;


Answered by: >NL_Dev

Credit:> Stack Overflow


Suggested blogs:

>How to add the total amount for each index list Vuejs?

>How to set up a dynamic grid based on flex or grid in Vuejs?

>How to get all the rows selected in Vuejs?

>How do I fix an invalid route component in the new VueJs Project?

>How can I replace this.$parent in composition API in Vuejs?

>What is meant by progressive framework?

>Why logged user object is all strings in Vuejs and Laravel 10?

>How to get the date and time and display it in a defineProps in Vuejs?



Submit
0 Answers