Samuele1818
Samuele1818

Reputation: 434

React change state of one component from another

I need to change the state of my sidebar component from another component.

My code:

Sidebar.tsx >

const SideBar: React.FC = () => {

    const [open, setOpen] = useState<boolean>(false);

    function switchSidebar() {
       setOpen(!open);
    }

    const bar = useMemo(() => <Menu open={open} sidebar={true} />, [open])

        return (
           <>
              <SidebarButton /> 
              { bar }
           </>

} 

SidebarButton.tsx >

export const SidebarButton:React.FC = () => {
  return(
        <svg xmlns="http://www.w3.org/2000/svg" onMouseDown={/* ? */}>
            <path stroke="currentColor" strokeWidth={3} d="M0 1.5h28M0 10.5h28M8 19.5h20"/>
        </svg>
 )
}

Menu.tsx >

const Menu: React.FC = ({sidebar, open, data = HeaderData}) => {
       return (
         <ul>
            <SidebarButton /> 
            { /* Other things to render */ }
         </ul>
       )
}

How you can see I need a method to change the state that is contained in Sidebar from SidebarButton.

Upvotes: 0

Views: 690

Answers (1)

Oscar
Oscar

Reputation: 132

You can pass the setOpen function as a prop to the SidebarButton component and then simply call the setOpen function to change the value.

<SidebarButton setOpen={setOpen} />

If you would like to also call it from the menu component then you may need to move the declaration of open to a higher component that is common between Sidebar and Menu since props can only be passed downwards.

Upvotes: 1

Related Questions