Reactjs Basic Routing Example With Component

04-Apr-2023

.

Admin

Reactjs Basic Routing Example With Component

Hello Guys,

In this quick example, let's see react routing on button click. let’s discuss about react js routing and navigation. let’s discuss about react routing between components. This tutorial will give you simple example of react routing in app.js.

You have to use routing in react project first you have to install route package then you can use routing. and also you have to import in your component. In default route you must use "exact". In this example i used "" with routing.

Routing Package Install Command


npm install react-router-dom

/src/App.js file

import React from 'react';

import './App.css';

import Header from './Header';

function App() {

return (

<div>

<Header />

</div>

);

}

export default App;

/src/Header.js file

import React from 'react'

import {

BrowserRouter as Router,

Switch,

Route,

Link

} from "react-router-dom";

import Home from './Home';

import AboutUs from './AboutUs';

import ContactUs from './ContactUs';

class Header extends React.Component{

render(){

return(

<div>

<div className="row">

<div className="col-md-12">

<Router>

<nav className="navbar navbar-expand-sm bg-dark navbar-dark">

<ul className="navbar-nav">

<li className="nav-item active">

<Link to="/" className="nav-link">Home</Link>

</li>

<li className="nav-item">

<Link to="/about-us" className="nav-link">About Us</Link>

</li>

<li className="nav-item">

<Link to="/contact-us" className="nav-link">Contact Us</Link>

</li>

</ul>

</nav>

<br />

<Switch>

<Route exact path="/">

<Home />

</Route>

<Route path="/about-us">

<AboutUs />

</Route>

<Route path="/contact-us">

<ContactUs />

</Route>

</Switch>

</Router>

</div>

</div>

</div>

)

}

}

export default Header;

All other component are same as home component here i give you one component example.

/src/Home.js file

import React from 'react'

class Home extends React.Component{

render(){

return(

<div>

<h4>This is Home Component.</h4>

</div>

)

}

}

export default Home;

/src/AboutUs.js file

import React from 'react'

class AboutUs extends React.Component{

render(){

return(

<div>

<h4>This is About Us Component.</h4>

</div>

)

}

}

export default AboutUs;

I hope it can help you...

#React.js