简体   繁体   中英

handling style in functional component in react js

i am using a functional component, and have created a sidebar menu structure, with parent child way (kind of dropdown). So when I click on parent an active class should be toggle and on its next element toggle style> display> none/block.

        <Fragment key={index}>
          <button
            className='dropdown-btn bg-transparent haschild'
            style={{ border: 'none' }}
          >
            {data.name} <i className='fas fa-chevron-right'></i>
          </button>
          <div 
            className='dropdown-container'>
            <Content
              config={menuItem.children}
              children={true}
            />
          </div>
        </Fragment>

and on use effect

useEffect(() => {
   var dropdown = document.getElementsByClassName("haschild");
   var i;
   for (i = 0; i < dropdown.length; i++) {
     dropdown[i].addEventListener("click", function () {
       this.classList.toggle("active");
       var dropdownContent = this.nextElementSibling;
       if (dropdownContent.style.display == "none") {
         dropdownContent.style.display = "block";
       } else {
         dropdownContent.style.display = "none";
       }
     });
   }
 },[]);

wherever i have class has child on that element i have to toggle a class active and on its next siblings, want to add style attr with display

When using a Framework like react that doesn't directly manipulate the DOM it's not recommended to change style like that. What you should do instead is to either work with classes and toggle them in react, not using document.getElementsByClassName or similar functions.

This could look something like this, depending on your need:

const ToggleButton = () => {
  const [active, setActive] = useState(false);
  return (
    <button onClick={() => setActive(prev => !prev)} className={active ? 'active' : 'inactive'}>
      Toggle active
    </button>

  );
};

This component would render a button that can be clicked to toggle between the classes active and inactive . The rest can and perhaps should be done with purely CSS.

Modern CSS combinators like ~ can be used to affect following elements. You can read more about CSS combinators here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM