In React, navigation and routing are typically handled using a library called React Router. React Router allows you to define routes in your application and navigate between them without reloading the page, which is essential for building single-page applications (SPAs). Here’s a guide to get you started with navigation and routing in React using React Router.
1. Install React Router
npm install react-router-dom
2. Set Up the Router
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
);
}
export default App;
3. Create Component Pages
Create the components that you want to navigate between. For instance, you can create Home, About, and Contact components.
// Home.js
import React from 'react';
function Home() {
return Home Page
;
}
export default Home;
// About.js
import React from 'react';
function About() {
return About Page
;
}
export default About;
// Contact.js
import React from 'react';
function Contact() {
return Contact Page
;
}
export default Contact;
4. Navigation Links
You can use the Link component from react-router-dom to create navigation links.
import { Link } from 'react-router-dom';
function Navigation() {
return (
);
}
export default Navigation;
5. Integrate Navigation
Now, include the Navigation component in your main App component so that the navigation links are displayed.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
import Navigation from './Navigation';
function App() {
return (
);
}
export default App;
6. Using useHistory for Programmatic Navigation
You can use the useHistory hook to navigate programmatically.
import React from 'react';
import { useHistory } from 'react-router-dom';
function SomeComponent() {
let history = useHistory();
function handleClick() {
history.push('/about');
}
return (
);
}
export default SomeComponent;
7. Nested Routes
You can use the useHistory hook to navigate programmatically.You can create nested routes by defining routes within other components.
// NestedComponent.js
import React from 'react';
import { Route, Link, useRouteMatch } from 'react-router-dom';
function NestedComponent() {
let { path, url } = useRouteMatch();
return (
Topics
-
Topic 1
-
Topic 2
);
}
function Topic() {
let { topicId } = useParams();
return Requested topic ID: {topicId}
;
}
export default NestedComponent;
Integrate the NestedComponent into your main app.
import NestedComponent from './NestedComponent';
function App() {
return (
);
}