How to redirect to another page in React JS
Cover Image of How to redirect to another page in React JS |
In React, you can redirect to another page or route by using the `react-router` library, which is commonly used for handling routing in React applications. Here's how you can perform a simple redirection to another page:
1. First, make sure you have `react-router-dom` installed. You can install it using npm or yarn:
npm install react-router-dom
# or
yarn add react-router-dom
2. Import the necessary components from `react-router-dom` in your React component:
javascript
import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom';
3. Set up your routing with `Router`, `Route`, and `Redirect` components:
javascript
import React from 'react';
import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom';
const App = () => {
return (
<Router>
<div>
<ul>
<li>
<Link to="/page1">Page 1</Link>
</li>
<li>
<Link to="/page2">Page 2</Link>
</li>
</ul>
<Route path="/page1" exact component={Page1} />
<Route path="/page2" exact component={Page2} />
{/* You can use Redirect to perform a redirection */}
<Redirect from="/" to="/page1" />
</div>
</Router>
);
};
const Page1 = () => <h2>Page 1</h2>;
const Page2 = () => <h2>Page 2</h2>;
export default App;
In this example, we've set up a simple React application with two pages, Page 1 and Page 2, and a default redirect from the root URL (`"/"`) to `"/page1"`. When you access the root URL, it will automatically redirect to Page 1. You can replace `"/page1"` with the path you want to redirect to.
Post a Comment