Home > Software engineering >  ReactJS global state toggle
ReactJS global state toggle

Time:04-03

I am new to reactJS and stuck in an issue. i have a button in header that needs to toggle a class 'show' in a menu which is in some other file. I tried to use global state but do not know how to do that. here is what i did;

LAYOUT FILE

import React, { useState } from "react";
// importing header / menu etc.

function LayoutHome({ children }) {
const [state, setState] = React.useState({ MsgMenu: 'messages-dropdown' });
const handleOpenMsgMenu =  (e) => {        
    e?.preventDefault();
    setState({MsgMenu:'messages-dropdown show'});
};
return (
    <>
        <Header handleOpenMsgMenu={handleOpenMsgMenu} />
        <MessageMenu  handleOpenMsgMenu={state.MsgMenu} />
        {children}
        <Footer />


    </>
);
}

HEADER

import React, { useState } from "react";
function Header({handleOpenMsgMenu}) {
    <button type="button" onClick={handleOpenMsgMenu} className="header-notification-btn">MENU</button >
}

MENU

import React, { useState } from "react";
function MessageMenu({handleOpenMsgMenu}) {
    <div id="messages-dropdown" className={handleOpenMsgMenu}>
    // CONTENT
    </div>
}

CodePudding user response:

You can toggle state with !value and then change your class depending on that value

    setMenu(() => {
      return {
        ...menu,
        show: !menu.show // toggle
      };
    });

I've made a sample here

For the global state, check out Context or Redux

CodePudding user response:

To achieve this you can use useState hook to toggle the display of the Menu. create a new toggle state in global and pass it onto the menu component. below is the complete code.

import React from "react";

export default function App({children}) {
  const [state, setState] = React.useState({ MsgMenu: 'messages-dropdown' });
  const [toggle, setToggle] = React.useState(false);

const handleOpenMsgMenu =  (e) => {        
    e?.preventDefault();
    setToggle(!toggle);
};

return (
    <>
        <Header handleOpenMsgMenu={handleOpenMsgMenu} />
        <MessageMenu  handleOpenMsgMenu={state.MsgMenu} toggle={toggle} />
        {children}
    </>
);
}

// Header

import React from "react";
    function Header({handleOpenMsgMenu}) {
      return <button type="button" onClick={handleOpenMsgMenu} className="header-notification-btn">MENU</button >
    }

// Menu

import React from "react";
    function MessageMenu({handleOpenMsgMenu, toggle}) {
      return <div id="messages-dropdown" style={{display: toggle?"block":"none"}}>
      <ul>
        <li>
          {handleOpenMsgMenu}
        </li>
      </ul>
      </div>
    }
  • Related