PaddyCooper08
PaddyCooper08

Reputation: 131

How to use react-router inside of a method

I'm new to react and react router dom(and javascript in general), and I've been racking my brain and googling all over the place but I can't figure out how to redirect someone in a method like exampleMethod() {}. I then call said method in an onClick function on a button. Here's my code for the button:

<Button color="secondary" onClick={this.rejoinPrevRoom}>
     Rejoin previous room
</Button>

The button is inside a method called renderHomepage which is then called if there is a room code in the state inside the main render function. The code for rejoinPrevRoom:

rejoinPrevRoom() {
    console.log("Debug: A");
    console.log(this.state.roomCode);

    return <Redirect to={`/room/${this.state.roomCode}`} />;
  }

It successfully logs a code so there is one but I don't know why it doesn't redirect them. Any help would be appreciated greatly Thank you, Paddy

Upvotes: 1

Views: 423

Answers (3)

Danial
Danial

Reputation: 1633

If the component is inside a BrowserRouter, you can use history to do that.

rejoinPrevRoom() {
    console.log("Debug: A");
    console.log(this.state.roomCode);

    this.props.history.replace(`/room/${this.state.roomCode}`);
}

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 202638

You cannot return JSX from a callback handler and expect it to have any effect on what the component is returning to render to the DOM. In this case you can either set some state to conditionally render a Redirect component as part of the render return, or use the history object to issue an imperative redirect via history.replace (not history.push).

rejoinPrevRoom() {
  console.log("Debug: A");
  console.log(this.state.roomCode);

  this.props.history.replace(`/room/${this.state.roomCode}`);
}

If this component is not rendered directly by a Route component via the component, render, or children prop, then you can decorate it with the withRouter Higher Order Component in order to have the route props injected as props and have the history object available as this.props.history.

Update

In order to inject the route props change your HomePage export from

export default class HomePage extends Component {
  ....
}

to

class HomePage extends Component {
  ....
}

default export withRouter(HomePage);

Upvotes: 2

glinda93
glinda93

Reputation: 8459

If you're using React hooks you can redirect like the following:

const history = useHistory();

rejoinPrevRoom() {
    console.log("Debug: A");
    console.log(this.state.roomCode);

    history.push(`/room/${this.state.roomCode}`);
}

If you're using class components:


rejoinPrevRoom() {
    console.log("Debug: A");
    console.log(this.state.roomCode);

    const {history} = this.props;
    history.push(`/room/${this.state.roomCode}`);
}

Upvotes: 1

Related Questions