Example of Route Component
Code: Let’s consider a simple example to illustrate the usage of the Route component 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
//About.js import React from 'react' const About = () => { return ( <h1>About</h1> ) } export default About |
Javascript
//Contact.js import React from 'react' const Contact = () => { return ( <h1>Contact</h1> ) } export default Contact |
Javascript
//NotFound.js import React from 'react' const NotFound = () => { return ( <h1>NotFound</h1> ) } export default NotFound |
Output:
Explanation of Output:
- We import the Route component from ‘react-router-dom’.
- Inside the Router component, we define three routes using Route.
- Each Route specifies a path and the corresponding component to render when the URL matches that path.
Route Component in React Router
React Router is a popular library used for managing routing in React applications. At its core lies the Route component, which plays a pivotal role in defining the relationship between URLs and corresponding components.
In this article, we’ll delve into the intricacies of the Route component, exploring its purpose, syntax, and practical usage.
Table of Content
- What is the Route Component?
- Why Use the Route Component?
- Breakdown of the Route Component in React Router
- Steps to Implement Route Component
- Example of Route Component
- Conclusion