React Route
React Router
- Routing is a process of directing users to the next page or different pages depending on their actions.
- A router is used to develop Single Page Web Applications.
- The router is used to build multiple routes in the application and when a user types a specific URL into the browser, and if the URL matches any route the user will be redirected to that particular route.
- React-router-dom is a reactJS package that plays an important role to display multiple views in a single page application.
- Command to install react-router-dom:
npm install react-router-dom --save
Implementation of Router
Step 1: Create a basic react app using the command:
npm create-react-app myProject
Step 2: Create different pages. Create different Components for our react-app.
Home.jsx
import React from "react";
const Home = () => {
return (
<div>
<h1>Home Page</h1>
</div>
);
};
export default Home;
About.jsx
import React from "react";
const About = () => {
return (
<div>
<h1>About Page</h1>
</div>
);
};
export default About;
ContactUs.jsx
import React from "react";
const ContactUs = () => {
return (
<div>
<h1>Contact Us Page</h1>
</div>
);
};
export default ContactUs;
Step 3: Install the react-router-dom package
npm install react-router-dom --save
Step 4: Import some components like BrowserRouter, Switch, route, and Redirect from the react-router-dom.
App.js
import "./App.css";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import ContactUs from "./components/ContactUs";
function App() {
return (
<>
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contactus" component={ContactUs} />
<Redirect to="/" />
</Switch>
</Router>
</>
);
}
export default App;
Home.jsx
import React from "react";
import { Link } from "react-router-dom";
const Home = () => {
return (
<div>
<h1>Home Page</h1>
<br />
<ul>
<li>
{/* Endpoint to route to Home component */}
<Link to="/">Home</Link>
</li>
<li>
{/* Endpoint to route to About component */}
<Link to="/about">About</Link>
</li>
<li>
{/* Endpoint to route to Contact Us component */}
<Link to="/contactus">Contact Us</Link>
</li>
</ul>
</div>
);
};
export default Home;
Step 5: Run the application by running the command
npm start