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 -
Install the React router in your application through npm. Open the terminal or command prompt.
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.
Home.js component:
import React from 'react'
const Home = () => {
return (
<div>Home</div>
)
}
export default Home
About.js component
import React from 'react'
const About = () => {
return (
<div>About</div>
)
}
export default About
Contact.js component
import React from 'react'
const Contact = () => {
return (
<div>Contact</div>
)
}
export default Contact
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