Setting Up React Router (v6)
๐ ️ 1. Install React Router
First, ensure you have React installed. Then, install React Router:
bash
Copy
Edit
npm install react-router-dom
๐งญ 2. Set Up the Router in Your App
In your main index.js or App.js file, wrap your application in a router:
jsx
Copy
Edit
// index.js or main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
๐ 3. Define Routes in App Component
Now set up your routes inside App.js:
jsx
Copy
Edit
// App.js
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import NotFound from './pages/NotFound';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
);
}
export default App;
๐งฉ 4. Create Your Page Components
Create simple components like:
jsx
Copy
Edit
// pages/Home.js
export default function Home() {
return <h1>Home Page</h1>;
}
// pages/About.js
export default function About() {
return <h1>About Page</h1>;
}
// pages/NotFound.js
export default function NotFound() {
return <h1>404 - Not Found</h1>;
}
๐ 5. Add Navigation
Use the Link component for navigation:
jsx
Copy
Edit
// components/Navbar.js
import { Link } from 'react-router-dom';
export default function Navbar() {
return (
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
);
}
Then import and use it in your layout or App.js.
✅ That's it!
You now have a working React Router v6 setup.
Learn React JS Course in Hyderabad
Read More
๐ React Router & Navigation
Best Practices for Managing Forms in React
Integrating React with Yup for Validation
Building a Dynamic Form Component
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment