DEV Community

Harit
Harit

Posted on

RRdom-6 post1

Hey folks, I know most of us were using react-router-dom-v5 before & the v6 must be a little bit confusing. But trust me they have made it more simpler in the latest version for routing of different pages. Breaking down all the concepts one by one for better understanding. Let's start๐Ÿ˜Š

What is react-router-dom?
It is a fully-featured client and server-side routing library for react.
Helps create and navigate between different URLs that make up your web application.
Provides unique URLs for different components in the app and makes the UI easily shareable with other users.
What we'll be covering from the new version -
Configuring routes.
Navigating programmatically
Dyanamic routes
Nested routes
Route parameters
Lazy loading
Installation -
npm install react-router-dom@6

Configuring routes:
Let's begin with the most common usage for routes.
Taking a scenario, suppose a user is on the home page & want's to visit the about page, vice versa.

To configure routes, we need to connect url in the browser, with our react app, for that react router provides a component called BrowserRouter, with which we need to wrap our entire app. We can simply do that in the index.js file.

// index.js file
import { BrowserRouter as Router } from "react-router-dom";
<Router>
     <App />
</Router>
Enter fullscreen mode Exit fullscreen mode

Create two components home, about and navbar for the UI.

// Home.js file
const Home = () => {
  return <div className="element">This is Home page</div>;
};
export default Home;

// About.js file
const About = () => {
  return <div className="element"> This is about page</div>;
};
export default About;
Enter fullscreen mode Exit fullscreen mode

In App.js we wrap home & about within Routes component & Route individually from the react-router-dom. The route has two parameters, path which reflects the path in the url & element which includes our components. Note - Here we don't need to add '/' before path expect for the root/ home url i.e. itself '/'.

// App.js
import { Route, Routes } from "react-router-dom";
import About from "./components/About";
import Home from "./components/Home";
import Navbar from "./components/Navbar";
import "./styles.css";
export default function App() {
  return (
    <div className="App">
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="about" element={<About />} />
      </Routes>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Edited Everydayyy after new learninggg ๐Ÿ˜€

Top comments (1)

Collapse
 
hardikdheer profile image
hardikdheer

Good bro..