React Router Dom ( Beginner's guide )
React-Router-Dom for Web applications, Using Routes instead of Switch (version 6)
Is this your first time using React-Router or you have been using it, however, you do not get your way around it. Anyway, welcome here, I was once like you when I started my coding journey.
in this article, you will be learning how to get your hands on React Router dom for beginners. I will take you through the What
and How
you should use in the simplest way.
What is React Router & React Router Dom?
React Router is a standard routing library for ReactJS, it helps with navigating through various pages and components in a React application. React router is the core package that contains the functionalities and components that make routing works for both web and mobile applications. on the other hand, React Router Dom is a specialized package that is used mainly for web-browsed application development.
Get started
To use React router, you will start by installing the react-router-dom
package using either npm
or yarn
.
//npm
npm install react-router-dom
//yarn
yarn add react-router-dom
You will need to import the BrowserRouter
in your index.js
file and wrap your App
component inside of it.
//index.js
import { BrowserRouter} from "react-router-dom"
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>,
);
The next thing to do is go to your App.js
file. import { Routes and Route }
and define your Routes. This can be done anywhere in your React app, however, it is best to be placed in the App.js
file.
whenever the URL
of your site changes, the React Router
will look out for the Routes
and render the elements in the Route
whose path matches the URL
of the React App.
//App.js
import { Routes, Route } from "react-router-dom";
import { Home } from "./Home";
import { About } from "./About";
import { contact } from "./Contact";
const App = () => {
return (
<Routes>
<Route path="/" element={<Home/>} />
<Route path="/about" element={<About/>} />
<Route path="/contact" element={<Contact/>} />
</Routes>
);
};
export default App;
NOTE : Routes
should be used instead of Switch
in React Router version 6 upward.
Handling navigation in React Router
comes with its own custom Link
similar to the normal anchor tag. This Link
helps enable the Re-rendering and Routing to work properly just like the anchor tag does.
//NavBar.js
const NavBar = () => {
return (
<nav>
<ul>
<li> <Link to="/" > Home </Link> </li>
<li> <Link to="/about"> About </Link> </li>
<li> <Link to="/contact"> Contact </Link> </li>
</ul>
</nav>
);
};
export default NavBar ;
Conclusion
Here we are!, so far you have learnt how to navigate through your React app pages using React Router. Creating well-organized and clean Routes is more achievable using React Router
.
You can visit React Router version 6 to learn more about it.
Happy coding :)