@filiberto
In React.js, you can redirect to a new route or page on button click using the history object. Here's an example of how you can achieve this:
First, you need to import the useHistory hook from react-router-dom in your component:
1
|
import { useHistory } from 'react-router-dom';
|
Then, inside your component function, you can initialize the history object using the useHistory hook:
1
|
const history = useHistory(); |
Next, create a function that will be called when the button is clicked. Inside this function, you can use the history.push method to redirect to a new route:
1 2 3 |
const handleClick = () => {
history.push('/new-route');
}
|
Finally, attach the handleClick function to the onClick event of the button:
1
|
<button onClick={handleClick}>Redirect</button>
|
When the button is clicked, the handleClick function will be called, which will redirect the user to the /new-route.