1

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");
      }

Shashank
  • 437
  • 2
  • 6
  • 21

9 Answers9

3

Use the Link component from react-router-dom:

<Link to="/profile">View profile</Link>

Check out the docs as well, they provide a lot of examples

Juviro
  • 180
  • 1
  • 7
3

You can call up the useHistory() hook to navigate.

import { useHistory } from "react-router-dom";

const yourComponent = () => {
  const history = useHistory();
  viewProfile = function() {
    history.push("/new-url");
  };
  return (
    <Button color="primary" onClick={viewProfile}>
      View Profile
    </Button>
  );
};

If you are using a class component you can wrap it withRouter() to gain access to the same history object.

import React from "react";
import { withRouter } from "react-router";

class YourComponent extends React.Component {
  viewProfile = function() {
    const { history } = this.props;
    history.push("/new-url");
  };

  render() {
    return (
      <Button color="primary" onClick={this.viewProfile}>
        View Profile
      </Button>
    );
  }
}

export default withRouter(YourComponent);
KyorCode
  • 1,477
  • 1
  • 22
  • 32
1

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!

Fernando
  • 280
  • 2
  • 10
0

Adding this solved my problem.

import { Redirect } from 'react-router'


      state = {
          redirect: false
         }

        const { redirect } = this.state;

        if (redirect) {
          return <Redirect to='/profile-page'/>;
        }


      viewProfile = function () {
          console.log("clicked");
          this.setState({ redirect: true })
      }

thanks @tarzen chugh, @Good Samaritan for you response

Shashank
  • 437
  • 2
  • 6
  • 21
0

Nomenclature is important when you are first learning a new framework :)

Strictly speaking a redirect will

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack

What you want is navigating to the profile page. There are two ways you can achieve this

  1. Through JSX Link.

  2. Programmatically with the history object.

tony
  • 1,274
  • 1
  • 11
  • 27
0

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class Test extends Component{
  constructor(props){
    super(props);
    this.state ={}
  }
  
  viewProfile = () => {
    const {history} = this.props;
    history.push('profile-page');
  }
}

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class Test extends Component{
  constructor(props){
    super(props);
    this.state ={}
  }
  
  viewProfile = () => {
    const {history} = this.props;
    history.push('profile-page');
  }
  render(){
    return(
      <Button
        color='primary'
        onClick={() => this.viewProfile()}>
        View Profile
      />
    );
  }
}
export default withRouter(Test);
Govind Soni
  • 320
  • 1
  • 2
  • 11
0

Use the useNavigate hook from react-router-dom. It's simple solution

import { useNavigate } from "react-router-dom"

const navigate = useNavigate();

const navigateDashboard = (event) => {
    navigate("/dashboard");
};

<Button color='primary' onClick={navigateDashboard}>View Profile</Button>
greeneley
  • 87
  • 7
-1

Here you can use withRouter HOC to do redirects.

import { withRouter } from "react-router";

class Component extends React.Component {
  viewProfile = function () {
     console.log("clicked");
     this.props.history.push('/main');
  }

  render(){
    return (
       <Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>        
    )
  }

}
export default withRouter(Component);

Ref: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

ma_dev_15
  • 1,176
  • 7
  • 18
-1

Do like this :-

<Button color='primary' onClick={() => this.viewProfile()}>View Profile</Button>

viewProfile= () => {
      return (
        <Redirect
          to={{
            pathname: "/profile-page",
          }}
        />
      );
  };
Shashwat Prakash
  • 434
  • 5
  • 14