React Router is a declarative library built on top of React to create dynamic routing in React applications. When we say dynamic routing, we mean routing that takes place when you app is rendering. Everything is considered a Component in React Router. The official docs are well-wriiten and more than enough to get started with.
So, let’s get started with React Router.
First and foremost, we need to import BrowserRouter, Link and Route from react-router-dom.
<Route path="/about" component={About} />Here, About component will have access to the history object. It comes in handy whenver we have to redirect to another page, with the use of history’s push method.
<Link to="/about">About</Link>Whenver we click on a link, the route will change. Here, when we click on the About link, it will simply take us to the /about route, and we can see the content in the About page.
<Route path="/about" component={About} />Here, when the path matches to /about, we want the About component to get rendered.
Check this CodeSandbox out below:
Here’s another simple example to understand the url parameters.
import React, { Component } from "react";
import "./styles.css";
import { BrowserRouter as Router, Link, Route } from "react-router-dom";
const Home = () => {
return <h2>Home</h2>;
};
const About = () => {
return <h2>About</h2>;
};
const Topic = props => {
return <h2>{props.match.params.topicId}</h2>;
};
const Topics = props => {
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${props.match.url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${props.match.url}/components`}>Components</Link>
</li>
<li>
<Link to={`${props.match.url}/props-v-state`}>Props v State</Link>
</li>
</ul>
// :topicId is like a placeholder here.
// We can access this topicID in our Topics component
// with the help of match object's url property.
<Route path="/topics/:topicId" component={Topic} />
<Route
exact
path={props.match.url}
render={() => <h3>Please select a topic</h3>}
/>
</div>
);
};
class App extends Component {
render() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);
}
}
export default App;Before moving any further, it’s important to know the behaviour of Switch component. Switch renders the very first route that matches.
<Switch>
<Route exact path="/" component={Home} />
<Route path="/will-match" component={WillMatch} />
<Route component={404Page} />
</Switch>Here, when we go to / route, Home will get rendered and when we go to /will-match, WillMatch will get rendered. If we go to any other route, say, /movies, the 404Page component will get rendered saying that the page you requested was not found.
Try this CodeSandbox.
Thank You for reading this article. Follow me on Twitter for more updates.