Redirect to a specific URL after clicking a button in React

To redirect a user to a specific page, the useHistory Hook from react-router-dom is convenient.

javascript
import React          from 'react';
import { useHistory } from 'react-router-dom';

const App = () => {

    const history = useHistory();
    
    const redirectMe = (url) => {
        
        // Redirects the user to url
        history.push(url);
        
    }
    
    return(
        
        <button onClick = {() => redirectMe('/')}>Click me to redirect</button>
        
    );

}

export default App;

Alternative

You can also redirect the user without using the useHistory Hook. Using window.location.href will do the job as well.

javascript
import React from 'react';

const App = () => {
    
    const redirectMe = (url) => {
        
        // Redirects the user to url
        window.location.href = url;
        
    }
    
    return(
        
        <button onClick = {() => redirectMe('/')}>Click me to redirect</button>
        
    );

}

export default App;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.