pmiranda
pmiranda

Reputation: 8450

ReactJS, redirect after render

Is there a way or how can I redirect after some return on render?

What I want is to do something like this:

render() {
  return(<div>You have no access</div>)
  // then redirect to "/"

I was thinking on create a component that only has a redirect in componentDidMount after 3 seconds, for example called <Redirect> then use it like this:

render() {
  return(<Redirect time=3> <div>You have no access</div> </Redirect>
  // then redirect to "/"

Redirect.js

componentDidMount() {
  // code for redirect using with this.props.time

Is there another way?

Upvotes: 0

Views: 486

Answers (1)

keikai
keikai

Reputation: 15166

Yes, you can achieve that kind of redirect.

Since you can pass data during routing, it's possible to pass the prev URL to this component, in order to replace the /, achieving return to prev page.

componentDidMount() {
  const intervalId = setInterval(this.timer, 1500);
  this.setState({ intervalId: intervalId });
}
componentWillUnmount() {
  clearInterval(this.state.intervalId);
}
timer = () => {
  this.props.history.push("/");
};

The only thing left is to make it a common component, or a HOC for auth check, based on the code demand.


enter image description here

Try it online:

Edit cranky-chatelet-quoy7

Upvotes: 1

Related Questions