Router In React js


Router in React js


React Router is the standard routing library for React, React Router is a collection of navigational components that compose declaratively with your application.

Here you will get more information about React Routing , 
if you want to work with React Router Dom , latest version 6-2-2 then u need to update your nod js as well as npm version also

React Router New Version v6.4.4


Example ::

In App. JS File it should show like this 


  import React from 'react';
  import { BrowserRouter, Route, Routes } from "react-router-dom";
  import { About } from './About';
  import { Home } from './Home';
  import { Services } from './Services';

  function App(){
    return(
      <div>

        <BrowserRouter>
          <Routes>
            <Route path='/' element={<Home />} />
            <Route path='/about' element={<About />} />
            <Route path='/services' element={<Services />} />

          </Routes>
        </BrowserRouter>

      </div>
    )
  }

  export default App;

 


For inner pages , like About | Services ... pages code seems to be like this,.. and this is Home page.

 
    import React from 'react'
    import './style.css';
    import { Link } from 'react-router-dom';

    export const Home = () => {
    return (
        <div>
            <header>
                <nav>
                    <ul>
                        <li><Link to="/">Home</Link></li>
                        <li><Link to= "/about">About</Link></li>
                        <li><Link to="/services">Services</Link></li>
                       
                    </ul>
                </nav>
            </header>

            <section>
                <h2>Welcome to Home Page</h2>
            </section>
        </div>
    )
    }  



useNavigate , hook for React-Router-DOM, with Button ::

 
  import React from 'react'
  import { Link } from 'react-router-dom';
  import { useNavigate } from 'react-router-dom';

  export const About = () => {

    var navigate = useNavigate();
    var goToContact =()=>{
      navigate ("/");
    }

    return (
      <div>
          <header>
              <nav>
                  <ul>
                      <li><Link to="/">Home</Link></li>
                      <li><Link to= "/about">About</Link></li>
                      <li><Link to="/services">Services</Link></li>                      
                  </ul>
              </nav>
          </header>

          <h2>About Page</h2>
          <p>this is about page</p>
          <button onClick={()=>goToContact()}>
            Go To Home Page
          </button>
      </div>
    )
  }
Page Not Found , element in routing

        <Routes>
          <Route path='/' element={<Home />} />
          <Route path='/about' element={<About />} />
          <Route path='/services' element={<Services />} />
          <Route path='*' element={<h2>Page Not Found</h2>} />
        </Routes>      

  * Download Source Code  on GitHUB