Search code examples
reactjsreact-router-dom

Redirect on button click in React


Can anyone please tell me how redirect works in react?

I'm from Angular background and trying to learn React.

I have a small application, where I want to redirect the user to profile component on click of a button.

This is a very basic requirement but there's no proper documentation available (or I'm not able to find one).

Any help will be appreciated.

Here's my code:

import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";

<BrowserRouter>
    <Switch>
      <Route path="/" exact render={props => <Index {...props} />} />
      <Route path="/login-page" exact render={props => <Login {...props} />} />
      <Route path="/profile-page" exact render={props => <Profile {...props} />} />
      <Route path="/dashboard" exact render={props => <Dashboard {...props} />} />
      <Redirect to="/" />
    </Switch>
  </BrowserRouter>,
<Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>

viewProfile = function () {
          console.log("clicked");
      }


Solution

  • React Router comes with a Link component that can be used for this. Just import it, set the destination in the to prop, and wrap your Button with it:

    import { Link } from "react-router-dom";
    
    <Link to='/profile-page'>
       <Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>
    </Link>
    
    viewProfile = function () {
        console.log("clicked");
    }
    

    Have a look at the React Router docs, they've got a lot of useful info!