1
render() {
 if(this.state.verified){
  return(<div>Verified</div>)
 }else {
   return(<Redirect to='/'/>)
 }
}

This is producing an error < Redirect> elements are for router configuration only and should not be rendered

This is how i understood rerouting should be done from react router docs. What is wrong with the code above and how should conditional re-routing done in react?

illiteratewriter
  • 3,204
  • 1
  • 16
  • 35

2 Answers2

1

From the error that you are getting, I am assuming that you are using a react-router version < v4. Before version 4, Redirect & Route components can only be children of Router component and can't be nested within the components. In those cases what you would need to do is to programmatically redirect to a different Route

componentWillUpdate(nextProps, nextState) {
    if(nextState.verified !== this.state.verified && !nextState.verified) { 
       //Programmatically Route here
    }
}
render() {
 if(this.state.verified){
  return(<div>Verified</div>)
 }
}

Check this on how to Programmatically change routes with react-router

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
0

I'm guessing the problem is that the component you're calling this method in is not being used inside of a ReactRouter. i.e. if your component is called MyComponent it should be called inside of the application router something like this:

const RoutedApp = () => (
  <BrowserRouter >
    <Switch>
      <Route path="/my_component" component={MyComponent} />
    </Switch>
  </BrowserRouter>
);
ReactDOM.render(<RoutedApp />, root); 
rainkinz
  • 9,042
  • 5
  • 34
  • 65