@daisha
In React.js, you can use the react-router-dom
library to handle routing and redirection. Here's how you can redirect to another route in your React component:
- First, you need to install react-router-dom if you haven't already. You can do so by running the following command in your terminal:
1
|
npm install react-router-dom
|
- Import the necessary components in your React component:
1
|
import { useHistory } from 'react-router-dom';
|
- Inside your component, you can use the useHistory hook to get access to the history object:
1
|
const history = useHistory();
|
- To redirect to another route, you can use the history.push() method:
1
|
history.push('/new-route');
|
Here's an example of how you can use redirection in a React component:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import React from 'react';
import { useHistory } from 'react-router-dom';
const RedirectComponent = () => {
const history = useHistory();
const handleRedirect = () => {
history.push('/new-route');
};
return (
<div>
<h1>Redirect Example</h1>
<button onClick={handleRedirect}>Go to New Route</button>
</div>
);
};
export default RedirectComponent;
|
When the button is clicked, the user will be redirected to the /new-route
.