This post shows how to achieve routing in a Reactjs app using React-Router-Dom and also how to pass props to a component.
Install the React-Router-Dom library:
npm install react-router-dom --save-prod
Now in App.js
, import the necessary components:
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
Now assuming that you have 2 different components to route to; LandingPage
and Signup
, we import them:
import LandingPage from './components/main/LandingPage';
import Signup from './components/authentication/Signup';
We put the following line in the render method of your App.js, preferably in the header
element:
<Link to="/">HOME</Link> | <Link to="/signup">SIGNUP</Link>
Here, we define 2 links that show which routes we are currently supporting in our web app.
Next, we define the routes:
<Route exact path='/' component={LandingPage} />
<Route path='/signup' component={Signup} />
Here, we define a component with each path address that we are supporting. The exact
keyword specifies that this component be used when this exact path address is mentioned. Otherwise, whenever we have a slash in the address, the LandingPage component would be routed to. So we specify it exactly.
Passing props in React Route
Say our LandingPage component is using props passed on by App.js using this.props. So how do we pass props with Route in the React Router Dom?
One possible way is to provide an inline function to the component mentioned in the route:
<Route exact path='/' component={() => <LandingPage name={'Ronaldo'} />} />
But the problem is that when we pass an inline function to a component in the route, this results in remounting of the component which causes overheads and possibly the application breaking as well.
To get around this, we use the render method which won’t result in remounting as the component:
<Route exact path='/' render={(props) => <LandingPage name={'Messi'} />} />
Our entire App.js file looks like this now:
import React from 'react';
import './App.css';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import LandingPage from './components/main/LandingPage';
import Signup from './components/authentication/Signup';
class App extends React.Component {
render() {
return (
<Router>
<div className="App">
<div className="container">
<header>
<h1>Your Title</h1>
<Link to="/">HOME</Link> | <Link to="/signup">SIGNUP</Link>
</header>
<Route exact path='/' render={(props) => <LandingPage name={'Ronaldo'} />} />
<Route path='/signup' component={Signup} />
</div>
</div>
</Router>
);
}
}
export default App;