Nicolas Ould Bouamama
Nicolas Ould Bouamama

Reputation: 273

Reactjs best practice for updating component depending on url

I was wondering what is the best practice in ReactJS to update a component's content depending on the url. Let say I have a navbar with some buttons in it. I want to display some of the buttons depending on the url.

For exemple, when the url is /home I want my navbar to be:

<nav>
     <button>Button 1</button>
     <button>Button 2</button>
     <button>Button 3</button>
</nav>

And when it's /about I want

<nav>
     <button>Button 2</button>
</nav>

My main component would be something like:

<Router>
    <Header />
    <Switch>
        <Route path="/home">
            <Home />
        </Route>
        <Route path="/about">
            <About />
        </Route>
     </Switch>
</Router>

So my navbar is in the <Header/> component. My first guess would be to use react-router to get the current url and then change what is rendered in the <Header/>

render() {
    let buttons
    if(location === "/home") {
        buttons = <button>Button 1</button><button>Button 2</button><button>Button 3</button>
    } else {
        buttons = <button>Button 2</button>
    }
    return (
       <nav>
           {buttons}
       </nav>
    )
}

Is it a good practice? Is there a better way? Should I use react-redux for the conditionnal rendering? (I'm new to react-redux and I'm trying to see all the possibilities)

P.S.: the code is not perfect because I typed it quickly direct in the message box sorry for that.

Upvotes: 0

Views: 329

Answers (1)

Abdullah Abid
Abdullah Abid

Reputation: 1661

you could use a ternary-operator, although there is nothing wrong with the implementation you have right now

    import React,{Fragment,Component} from 'react';
    import { useLocation} from "react-router-dom"; 

    class Header extends Component{
     let location = useLocation();
       render() {
        return (
           <nav>
              {
            location.pathname==='/home'? 
             (<Fragment>
              <button>Button 1</button>
              <button>Button 2</button>
              <button>Button 3</button>
             </Fragment>): (<Fragment>
              <button>Button 2</button>
             </Fragment>)    
            }
           </nav>
        )
    }
  }
}

and in your main component you could also use Route from react-router-dom

 import React,{Component} from 'react';
 import {BrowserRouter as Router,Route,Switch} from "react-router-dom";
 import Home from './Home';
 import About from './About';

  class App extends Component{
  render(){
   return(
      <Router>
       <Header />
       <Switch>
         <Route to="/home" component={Home}/>
         <Route to="/about" component={About}/>
       </Switch>
      </Router>
     );
    }
   }
  }

Again, this is just a personal preference rather than anything else,but it certainly cleans things up a little

Upvotes: 1

Related Questions