What is react-router-dom?
React Router DOM is a tool that helps manage navigation and routing in React applications. It allows you to create multiple pages or views within a single-page application, making it easier for users to navigate between different parts of the website. With React Router DOM, you can define routes for different URLs, ensuring that the correct components are rendered based on the user's location in the application. It simplifies the process of handling URLs and enables a smoother user experience by keeping the UI in sync with the URL.
Navigation | Routing |
Involves moving between different pages or components within the application. | Determines which component to render based on the current URL. |
Typically triggered by user actions such as clicking links or using browser navigation controls. | Managed by libraries like React Router DOM in React applications. |
Why we need it?
React Router DOM simplifies navigation in React applications by allowing developers to define routes, ensuring that the correct components are rendered based on the URL. It keeps the UI and URL synchronized for a smoother user experience, supports nested and dynamic routes, enables history management, and facilitates code splitting for better performance.
useHistory() hook
import React from 'react';
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
const handleClick = () => {
// Pushing a new URL onto the history stack
history.push('/new-page');
};
return (
<div>
<h1>Hello, React Router!</h1>
<button onClick={handleClick}>Go to New Page</button>
</div>
);
};
export default MyComponent;
We can simply see that history or browser url follows a pattern similar to stack
import React from 'react';
import './Home.css';
import { Link } from 'react-router-dom';
const Home = () => {
return (
<nav>
<ul>
<li>
<Link id="one" to="/">Home</Link>
</li>
<li>
<Link id="two" to="/about">About</Link>
</li>
<li>
<Link id="three" to="/service">Services</Link>
</li>
<li>
<Link id="four" to="/contact">Contact</Link>
</li>
</ul>
</nav>
);
};
export default Home;
import React from 'react'
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import Home from './components/Home';
import Contact from './components/Contact';
import About from './components/About';
import Service from './components/Service';
import NotFound from './components/NotFound';
const App = () => {
return (
<Router>
<div>
<Routes>
<Route exact path="/" Component={Home}/>
<Route path="/Contact" Component={Contact} />
<Route path="/About" Component={About} />
<Route path="/Service" Component={Service} />
<Route component={NotFound} />
</Routes>
</div>
</Router>
)
}
export default App
Above are sample codes how we can implement a navbar for a SPAs React type websites