This tutorial aims to guide you through the installation and setup process of React Router in a new React project. By the end of this tutorial, you will understand how to install the necessary dependencies, and configure your application to use React Router.
Prerequisites:
- Basic understanding of React and JavaScript is required.
- Node.js and npm installed on your local development machine.
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allowing you to create single page applications with navigation without page refresh as the user navigates.
React Router can be installed via npm. First, navigate to your React project directory in your terminal, then run:
npm install react-router-dom
After installing the React Router package, it's time to set it up within your project. The following example shows a basic use of React Router.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
}
export default App;
In this example, we wrap our Route components within the BrowserRouter (aliased as Router) and Switch components. The Route component is where we specify our routes. The path
prop is the pathname that will match our route, and component
prop is the component that will render when the route is matched.
In this tutorial, we've covered the basics of setting up React Router in a React project. We've learned how to install it using npm and how to use some of its main components: BrowserRouter, Route, and Switch.
For further learning, consider exploring more advanced topics such as nested routes, dynamic routes, and redirecting.
path
prop as the last Route inside your Switch component.import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}
export default Navbar;
Remember, practice is key when learning new concepts in programming. Keep creating new projects and experiment with different aspects of React Router.