Henrique Medina
Henrique Medina

Reputation: 69

React - Calling the function of other component

I'm very very new with React. Actually I started to learn today. I want to build a single sidebar component in a website.

I toggle a sidebar using UseState and a function called openHandler that verifies of the sidebar is already active.

I'm wondering how should I approach the toggle inside of the sidebar. How should I change the state of the sidebar if all the handle is done in the main file (App.js)

I'm really sorry if this question don't make sense.

Here is a SandBox example of what I'm talking about.

https://codesandbox.io/s/hopeful-framework-c4k1h

If someone know what should I learn to play with that would be great.

Thanks in advance

Upvotes: 1

Views: 297

Answers (2)

Youssef Egla
Youssef Egla

Reputation: 1601

I assume you want to be able to change the state of the sidebar by clicking a button from another sibling / child of a sibling component.

if that's the case you'll need to put the useState hook in the higher level parent, then pass the state / an it's setter method as a prop to the children that will use it.

here is an example of what I mean.

Parent Component

function parent() {
   // the sidebar state
   const [sidebar, setSidebar] = useState(false);

   // helper function that toggles state
   function toggle() {
      setSidebar(!sidebar);
   }

   return (
      <section className="Parent">
         { /* Conditional Render */
            sidebar ? 
               <Navbar stateManager={{toggle}} /> 
               : <HamburgerIcon stateManager={{toggle}}  />
         }
      </section>
   )

Navbar / HumburgerIcon

function Navbar({stateManager}) {
   // you now passed state and it's set method to the child
   const {toggle} = stateManager;

   return (
      <div onClick={toggle}>
        component content
      </div>
}

You can put them all in same file and still do the same thing.

Upvotes: 2

ilkerkaran
ilkerkaran

Reputation: 4344

you can pass the main handler to sidebar via props and bind it to insider toggle.

appjs

    ...
 <CartBox openHandler= {openHandler} className={ToggleCartState} />
    ...

cartBox.js

    ...
 <Toggle click={props.openHandler} />
    ...

Nice to read https://reactjs.org/docs/lifting-state-up.html

Upvotes: 2

Related Questions