Example of Routes Component
Code: Let’s consider an example to demonstrate the usage of routes in React Router:
Javascript
//App.js import React from 'react' ; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom' ; import Home from './components/Home' ; import About from './components/About' ; import Contact from './components/Contact' ; import NotFound from './components/NotFound' ; function App() { return ( <Router> <div> <Routes> <Route path= "/" element={<Home />} /> <Route path= "/about" element={<About />} /> <Route path= "/contact" element={<Contact />} /> <Route path= "*" element={<NotFound />} /> </Routes> </div> </Router> ); } export default App; |
Javascript
//Home.js import React from 'react' const Home = () => { return ( <h1>Home</h1> ) } export default Home |
Javascript
//Contact.js import React from 'react' const Contact = () => { return ( <h1>Contact</h1> ) } export default Contact |
Javascript
//About.js import React from 'react' const About = () => { return ( <h1>About</h1> ) } export default About |
Javascript
//NotFound.js import React from 'react' const NotFound = () => { return ( <h1>NotFound</h1> ) } export default NotFound |
Output:
Explanation of Output:
- We define routes for the Home, About, and Contact components using the Route component.
- The Switch component ensures that only one route is rendered at a time, preventing multiple routes from matching.
- If none of the defined routes match the current URL, the NotFound component is rendered.
Routes Component in React Router
Routes are an integral part of React Router, facilitating the navigation and rendering of components based on URL patterns.
In this article, we’ll delve into the concept of routes, understanding their role in React Router, and how to define and manage routes effectively.
Table of Content
- What are Routes ?
- Why Routes Are Essential ?
- Defining Routes
- Managing Routes
- Steps to implement Routes Component:
- Example of Routes Component
- Conclusion
Contact Us