Home > Software design >  How to open a modal component through an onClick from another component
How to open a modal component through an onClick from another component

Time:01-21

This question is related to this one. I am rewording to make it simple.

I have a main navigation component (MainNavigation.js) which is siblings with a Secondary Navigation Component(SecNavigation.js) under the Header component(Header.js).

What I want is when I click on a specific Link in the MainNavigation.js the whole SecNavigation.js to be displayed in a modal.

My problem here is that I don't quite grasp how should I go using useState, useContext or even if I need any of this.

CodePudding user response:

Hope this will clear something for you

What you need is a parent that handles the state and then it will pass it down to its children. Because the parent is keeping track of the children and what they are doing.

So what I have done it this:

App.js is the parent and I handle the state here. Then I just pass down the setIsModalShowing setState function to the MainNav that will call it when I press a button.

Then in the App.js I will show or hide the modal if the setIsModalShowing is true or false

inside of the modal I am showing SecNav and the modal also has the setIsModalShowing passed down so that you can click on the button to close is and that will set the state to false.

Does that makes sense to you ? or else I can try to explain it in another way

Code example

  •  Tags:  
  • Related