Mark As Completed Discussion

React Router

React Router is a third-party library that allows you to implement client-side routing in a React application. It provides a way to handle navigation and route rendering without the need for a full page refresh.

To get started with React Router, you will first need to install the react-router-dom package from npm. You can do this by running the following command:

SNIPPET
1$ npm install react-router-dom

Once you have installed React Router, you can import the required components and set up the routing in your application. Here is an example:

JAVASCRIPT
1import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
2import Home from './Home';
3import About from './About';
4import Contact from './Contact';
5
6function App() {
7  return (
8    <Router>
9      <div>
10        <nav>
11          <ul>
12            <li><Link to="/">Home</Link></li>
13            <li><Link to="/about">About</Link></li>
14            <li><Link to="/contact">Contact</Link></li>
15          </ul>
16        </nav>
17        <Switch>
18          <Route path="/about">
19            <About />
20          </Route>
21          <Route path="/contact">
22            <Contact />
23          </Route>
24          <Route path="/">
25            <Home />
26          </Route>
27        </Switch>
28      </div>
29    </Router>
30  );
31}
32
33export default App;

In this example, we import the necessary components from react-router-dom, such as BrowserRouter, Switch, Route, and Link. We then set up the routing using these components, defining routes for the /about, /contact, and / paths.

The Link component is used to create navigation links, which can be rendered as clickable elements in your application. The Route component specifies the component to render when a certain path is matched.

With React Router, you can easily create multi-page applications that update the URL without refreshing the entire page, providing a smoother user experience.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment