How to change the classname of next sibling in React js?

Viewed 28

I am trying to toggle the classname of the clicked element's next sibling element. Here the code:

<li>
 <Link onClick={(event) => event.currentTarget.nextElementSibling.classList.toggle("show")}>Nav Item A</Link>
   <ul className='submenu'>
     <li>
       <Link to="#0" onClick={closeMenu} >Submenu Item 1</Link>
     </li>
     <li>
       <Link to="#0" onClick={closeMenu} >Submenu Item 2</Link>
     </li>
   </ul>
</li>

<li>
 <Link onClick={(event) => event.currentTarget.nextElementSibling.classList.toggle("show")}>Nav Item B</Link>
   <ul className='submenu'>
     <li>
       <Link to="#0" onClick={closeMenu} >Submenu Item 3</Link>
     </li>
     <li>
       <Link to="#0" onClick={closeMenu} >Submenu Item 4</Link>
     </li>
   </ul>
</li>

But in console, after it toggles to "show", many errors come and it doesn't remove "show" on next click since it stucks. Errors are like this:

Uncaught ReferenceError: process is not defined

and

DevTools failed to load source map: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/browser-polyfill.js.map: System error: net::ERR_FILE_NOT_FOUND
history.js:47 Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')
    at createPath (history.js:47:1)
    at navigate (Link.js:104:1)
    at onClick (Link.js:51:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237:1)
    at invokeGuardedCallback (react-dom.development.js:292:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:306:1)
1 Answers

You're using React the wrong way. You need use to use state.

//Submenu.js
export const Submenu = (children) => {

 const[active, setActive] = useState("false")
 const toggleActive = () => setActive(!active);

 return(
  <div>{children}</>
 );

 //Main.js
<li>
   <Link onClick={toggleActive} />
   {active && <Submenu>....children....</Submenu>
  </li>
Related