Router in React

Router in React

What is Router?

React Router is a standanrd library for routing in react.

  • It enables the navugigation among views of various components in a react application, allows changing the browser URL,and keeps the UI in sync with the url.

  • React Routing is a fully-featured client and server-side routing library for react, a javascript library for building user interfaces.

  • React Router runs anywhere react runs.

  • Create react app doesn't include page routing by default.

  • React Router is the most popular solution.

  • It provide unique URL's for different component in the app and makes UI easily shareable with other users.

Installing & Setup

write these line in terminal and run for installing react-router in your app with latest version: npm i react-router-dom

After installing react router library, it will added in package.json file as dependency.

Configuring Routes:

  • We need to use 3 components from react-route-dom.

    1. BrowserRouter

    2. Routes

    3. Route

  • 1st step:- import BrowserRoute component from 'react-router-dom' inside index.js file on our react App like import { BrowserRouter } from 'react-router-dom';

  • Wrap our App component with BrowserRouter component like:-

import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
      <BrowserRouter>
          <App/>
      </BrowserRouter>
  </React.StrictMode>
);

BrowserRouter:- The BrowserRouter mean the App component are connect to the Browser URL.

  • 2nd step:- Now we have to create a folder called 'components' in our SRC folder and add 3 component called Home.js, About.js,Contact.js inside components folder.(add according to your choice).

  • 3rd step:- Import Routes and Route component from 'react-router-dom' in App.js File like:-

import { Route, Routes } from 'react-router-dom';
import Home from './components/Home';

function User() {
  return (
    <div>
      <Routes>
        <Route path='/' element={<Home/>}/>
        <Route path='/about' element={<Home/>}/> // go to about page
        <Route path='/contact' element={<Home/>}/> // goto contact page
      </Routes>
    </div>
  );
}

export default User

Routes:- Routes behave like a Boundary to have a bundle of routes in it.

Route:- Route is a way to connect any component ,having path or way of component.

Path:- Path mean you want where to go. The forward slash / always used for home page.

Element:- Element simplly mean a component.

Note:- In these route code not nessecery to write forward slash with component

If you write the path on web you also able to go to those page .

Mainlly ancor tag is re-render the web .so on the place of ancor tag we have to use Link tag .Link tag ignore the rendering the web if user want to go other component on the web.

import { Link } from 'react-router-dom'

function About(){
    return(
          <div> 
            <Link to="/" > Home </Link>
          </div>

);
}

to:- to is same work like path ,provide path of component.

If user enter in component so the component name show some change's init name so user understand that component isactive.

import { NavLink } from 'react-router-dom'

function About(){
    return(
          <div> 
            <NavLink to="/" > Home </NavLink>
          </div>

);
}

if user click on the about option in navbar so the about show her another text color .her css file like:-

.active{
    color:gray;
}

Errror Page Route

Every Website needs a 404 page if the URL does not exist or the URL might have been changed. To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple react component called PagenotfoundComponent.

code like:- <Route Path="*" element={<Error/>} />

Pagenotfind code write in Error component file.

Nested Routing

Home » React » React Js Nested Routes using React Router DOM 6 Tutorial

React Js Nested Routes using React Router DOM 6 Tutorial

Nested routes in React allow the parent component to have holistic control over the child components from the routing context.

import { Routes, Route} from 'react-router-dom'

function App(){
    return(
          <div> 
            <Routes>
                <Route Path="/" Element={<Home/>}>
                    <Route Path="About" Element={<About/>}/>
                    <Route Path="contact" Element={<Contact/>}>
                </Route>
            </Routes>
          </div>

);
}

Simpllly means a component have many component's.

Question:- Those nested components does not work properlly or dont show data on the web page so what we do?

For the componenet properlly work we will use a outlet tag in parent component.

import {outlet} from 'react-router-dom'
function Home(){
    return(
          <div> 
            <Navbar/>   //navbar component
               <outlet/>
          </div>

);
}

useNavigate

It helps to go to the specific URL, forward or backward pages. In the updated version, the React Router’s new navigation API provides a useNavigate() hook which is an imperative version to perform the navigation actions with better compatibility.

User want to go back to home page from any component like:-

import {useNavigatet} from 'react-router-dom'
function About(){
const navigate= useNavigate();

const gotohome = ()=>{
navigate("/Home");
};
    return(
          <div> 
          <h1> About page</h1>
          <button onClick={()=> gotohome()}>Go to home</button>
          </div>

);
}

History check

If user want to check the last page opened at last time on the web

import {useNavigatet} from 'react-router-dom'
function About(){
const navigate= useNavigate();

const gotohome = ()=>{
navigate("/Home");
};
    return(
          <div> 
          <h1> About page</h1>
          <button onClick={()=> gotohome()}>Go to home</button>
          <button onClick={navigate(-1)}>Go back</button>
          </div>

);
}

HAPPY LEARNING...