I have navbars and some tabs.
My React is constructed like below
...
return (
<>
<Navbar />
<Router>
<Route .... ..... component=Component1 />
<Route .... ..... component=Component2 />
</Router>
</>
)
...
But for some reason, I want to insert different button groups for Component1 into right of navbars.
Now I solve this problem by adding navbar in every components and put buttons in each navbar (component1, component2, component3).
It works, but if my tab count is 10, I have to copy Navbar for 10 times.
I don’t want this.
I ‘ll really appriciate for any help.
2
Answers
What you can do is instead of adding navbar in each component maintain one state in App or context that will keep track of which component is rendered and based on the component you can update the navbar.
The other approach could be if you are using different routes than based on route you can update the navbar. You can use
useLocation()
hook for the purpose or can usewindow.location.pathname
For example
You can use redux to solve this problem.
Steps:
-Create redux for storing navbar-right-buttons.
-Everytime each component is rendered, update navbar-right-buttons with what you want.
-In
Navbar
you can useuseSelector
to get buttons and use them.Thanks.