Page Content:
1.Router – Introduction
2.Router – Installation
3.Router – Create Component
4.Router – Add a Router
1.Introduction:
1.React Router is the standard routing library for React.
2.“React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought.”
2.Installation:
A simple way to install the react-router is to run the following code snippet in the command prompt window:
C:\Users\username\Desktop\reactApp>npm install react-router
C:\Users\username\Desktop\reactApp>npm install react-router-dom
3.creat component:
we will create four components. The App component will be used as a menu. The other three components (Home), (About), and (USers) are rendered once the route has changed.
App.jsx
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
<Router>
<div>
<nav>
<h2><b>React Router Example</b></h2>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/users">
<Users />
</Route>
<Route exact path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Users() {
return <h2>Users</h2>;
}
4.Add a router:
Now lets add router to App:
<Router>
<div>
<nav>
<h2><b>React Router Example</b></h2>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/users">
<Users />
</Route>
<Route exact path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
main.js
import './index.css';
import App from './App';
ReactDOM.render(<App />, document.getElementById('app'))
When the app runs, we will see three clickable links that can be used to change the route.
