Shubham
Shubham

Reputation: 1191

React Router: Create header for specific routes

Please have a look at the below routes.

import React from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import {
  Home, 
  Contact, 
  Jobs, 
  Careers, 
  Dashboard, 
  Group
} from '../container'

// ?
const Header = () => {
  return (<div style={{backgroundColor: 'red'}}> Test Custom header </div>)
}

// 
const Routes = () => (
  <Router>
    <Switch>
      <Route exact path='/' component={ Home } />
      <Route exact path='/contactus' component={ Contact }></Route>
      <Route exact path='/jobs' component={ Jobs } />
      <Route exact path='/careers' component={ Careers } />
    
      {/** header */}
      {/** Render Header component (only once) only for the dashboard and group component  */}
      <Route exact path='/dashboard' component={ Dashboard } />
      <Route exact path='/group' component={ Group } />
    </Switch>
  </Router>
)

export default Routes

Here, I want to add a common header (Header component) only for the /dashboard and /group route and this header component should be rendered only once. I tried some approaches:

Could you please suggest a good approach for this case?

Upvotes: 1

Views: 1350

Answers (1)

Jan-Philipp Marks
Jan-Philipp Marks

Reputation: 1539

I think the best way to do that is to add a Route for each header and pass an array of paths to path on the routes where you want to show certain header.

<Switch>
  <Route path=["/dashboard", "/group"] component={Header} /> 
  <Route exact path="/dashboard" component={Dashboard} />
  <Route exact path="/group" component={Group} />
  ...other Routes
</Switch>

Hope this works and helps :)

Upvotes: 1

Related Questions