First of all we need to add React Router to an existing project, the first thing you should do is install the necessary dependencies with the tool (npm / yarn) of your choice:
npm install react-router-domThen we have to create different components(Home , About , Contact ) in component folder , please check below image for ref...
Import all components in app.js file and also import BrowserRouter , Routes , Route component from "react-router-dom".
App.js code
import './App.css';
import About from './component/About'
import Contact from './component/Contact'
import Home from './component/Home'
import Header from './component/Header'
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
function App() {
return (
<div className="App">
<BrowserRouter>
<Header />
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/about" exact element={<About />} />
<Route path="/contact" exact element={<Contact />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
About.js File codeimport React from 'react'
export default function About() {
return (
<div>
<h1>This is About page</h1>
</div>
)
}
Header.js codeimport React from 'react'
export default function Header() {
return (
<div>
<a href='/' >Home</a>
<a href='/about' >About</a>
<a href='/contact' >Contact</a>
</div>
)
}
Output :
0 Comments
Post a Comment