React Button onClick Redirect Page
When working with React, you may come across a situation where you need to redirect the user to another page when a button is clicked. In this blog post, we will explore different approaches to achieve this functionality.
Approach 1: Using React Router
If you are already using React Router in your project, you can easily redirect the user to another page by utilizing the history
object provided by React Router.
First, make sure you have React Router installed by running the following command:
npm install react-router-dom
Next, import the necessary components:
import React from 'react';
import { useHistory } from 'react-router-dom';
Then, define your button component and use the useHistory
hook to access the history
object:
const MyButton = () => {
const history = useHistory();
const handleClick = () => {
history.push('/new-page');
};
return (
);
};
By calling the push
method on the history
object and passing the desired URL as an argument, you can redirect the user to the specified page when the button is clicked.
Approach 2: Using window.location
If you are not using React Router in your project, you can still achieve the desired functionality by utilizing the window.location
object.
In this approach, you can directly set the window.location.href
property to the desired URL when the button is clicked.
const MyButton = () => {
const handleClick = () => {
window.location.href = '/new-page';
};
return (
);
};
By assigning the desired URL to the window.location.href
property, the user will be redirected to the specified page when the button is clicked.
Conclusion
In this blog post, we explored two different approaches to redirecting a user to another page when a button is clicked in a React application. If you are already using React Router, you can use the history
object provided by React Router. Otherwise, you can directly set the window.location.href
property to achieve the same result. Choose the approach that best suits your project’s needs.
Happy coding!
Leave a Reply