skip to Main Content

I have navbars and some tabs.

My React is constructed like below

...
return (
  <>
    <Navbar />
    <Router>
      <Route .... ..... component=Component1 />
      <Route .... ..... component=Component2 />
    </Router>
  </>
)

...

enter image description here

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


  1. 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 use window.location.pathname

    For example

    <Route path="/component1" render={<Component1 />} />
    <Route path="/component2" render={<Component2 />} />
    
    function Navbar(){
      const location = useLocation();
      const pathname = location.pathname;
      
       if(pathname === "/component1"){ 
        return ( // return navbar for component 1 )
       }
    
       return ( // return default navbar )
    }
    
    Login or Signup to reply.
  2. 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 use useSelector to get buttons and use them.


    Thanks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search