1

How can I pass parameters to all my routes through <Routes />?
This is my Routes.js.

import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';

import Repos from './Repos';
import Org from './Org';
import Profile from './Profile';

class Routes extends Component {
  render() {
    return (
        <Switch>
          <Route exact path="/" render={() => (
           <Redirect to='/profile' />
          )} />
          <Route exact path="/profile" component={Profile} />
          <Route exact path="/repos" component={Repos} />
          <Route exact path="/org" component={Org} />
        </Switch>
    );
  } 
}

export default Routes;

This is how I am calling the routes component from Dashboard.js.

import React from 'react';

import Routes from './Routes';
import Header from './Header';

const Dashboard = props => {
  return (
    <div>
      <Header />
      <Routes />
    </div>
  );
};

export default Dashboard;

I need to pass common props to all my routes through <Routes />. How can i do it?

Akash
  • 45
  • 5

1 Answers1

0

You can use the Route's render prop instead of the component prop and spread all the Routes props and the route props on your components.

class Routes extends Component {
  render() {
    return (
      <Switch>
        <Route exact path="/" render={() => <Redirect to="/profile" />} />
        <Route
          exact
          path="/profile"
          render={props => <Profile {...this.props} {...props} />}
        />
        <Route
          exact
          path="/repos"
          render={props => <Repos {...this.props} {...props} />}
        />
        <Route
          exact
          path="/org"
          render={props => <Org {...this.props} {...props} />}
        />
      </Switch>
    );
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • 1
    Thanks Tholle. That worked. Is there any way to do it using component instead of render? – Akash Aug 10 '18 at 19:14
  • @AkashdeepSamantra You're welcome! I can't say with 100% certainty, but I'm pretty sure you can't. That would be news to me, at least. – Tholle Aug 10 '18 at 19:15