skip to Main Content

i make toogle in react using useState like this sample component

import React, { useState, useEffect } from "react";
const Button = () => {
  const [show, setShow] = useState(false)
  
  useEffect(() => {
    function listing () {
      setShow(false)
  }
    if (show && true) {
      window.addEventListener("click", listing, true)
      console.log("test")
    }
  })
  return (
    <>
      <button onClick={() =>
        setShow(true)
      }>
      test
      </button>
      {show && <div> show text</div>}
    </>
  )
}
export default Button

but if button already true value and im click again button value is true and im click window element be false, so element target div show cant gone, but is same if im give setShow(!show) on listener onclick button. target element keep show if already true

2

Answers


  1. Chosen as BEST ANSWER

    im find answer https://stackoverflow.com/a/45323523/16945930

    and i add liltle code

    import React,{ useState, useEffect, useRef } from 'react';
    
     function useComponentVisible(initialIsVisible) {
        const [isComponentVisible, setIsComponentVisible] = useState(initialIsVisible);
        const ref = useRef(null);
    
        const handleClickOutside = (event) => {
            if (ref.current && !ref.current.contains(event.target)) {
                setIsComponentVisible(false);
            }
        };
    
        useEffect(() => {
            document.addEventListener('click', handleClickOutside, true);
            return () => {
                document.removeEventListener('click', handleClickOutside, true);
            };
        }, []);
    
        return { ref, isComponentVisible, setIsComponentVisible };
    }
    
    const DropDown = () => {
      const { ref, isComponentVisible, setIsComponentVisible } = useComponentVisible(false);
      return (
        <>
      
         <div ref={ref}>
          <a onClick={()=> {setIsComponentVisible(!isComponentVisible)}}>show</a>
            {isComponentVisible && (<p>Dropdown Component</p>)}
         </div>
         </>
      );
    
    }
    export default DropDown
    

  2. I think this is something that you want to create:

    import React, { useState } from "react";
    export const Button = () => {
      const [show, setShow] = useState(false);
      return (
          <button onClick={() => setShow(!show)}>
           {show ? "active" : "inactive" }
          </button>
    
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search