Pages

How to route between different components in React.js?

React router is a standard library to navigate among various components in a React application. It allows changing the browser URL and keeps the UI in sync with the URL.

In an application, there may be four components, such as Home, About, Contact, and Footer.


We need a react router to navigate between these components.


Create an react app using the following command - 


npx create-react-app Your_App_Name


Install the React router in your application through npm. Open the terminal or command prompt.


npm install - - save react-router-dom or npm i react-router-dom


After installing React router, import it in App.js file - 


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


Create multiple components:

Now, we will create 2 or 3 component with name Home.js ,About.js, Contact.js and Footer.js


Note: First letter of the word should be in capital letter.


  1. Home.js component:


import React from 'react'


const Home = () => {

  return (

    <div>Home</div>

  )

}


export default Home


  1. About.js component


import React from 'react'


const About = () => {

  return (

    <div>About</div>

  )

}


export default About


  1. Contact.js component


import React from 'react'


const Contact = () => {

  return (

    <div>Contact</div>

  )

}


export default Contact


  1. Footer.js component


import React from 'react'


const Footer = () => {

  return (

    <div>Footer</div>

  )

}


export default Footer


Now, let us include the router to the application.


import logo from './logo.svg';

import './App.css';

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

import Home from './Home';

import About from './About';

import Contact from './Contact';

import Footer from './Footer';


function App() {

  return (

    <div className="App">

      <BrowserRouter>

      <Routes>

      <Route exact path="/" element={<Home />}></Route>

      <Route exact path="/about" element={<About />}></Route>

      <Route exact path="/contact" element={<Contact />}></Route>

      <Route exact path="/footer" element={<Footer />}></Route>

      </Routes>

      </BrowserRouter>

    </div>

  );

}


export default App;


Final thoughts: This is the complete ReactJS router tutorial, and it will help coders create different components in ReactJS and route between them. 




No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...