Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Redirect Conditional

I'm trying to make a button that only redirects the user to a new page after validation is completed correctly.

Is there a way of doing something like this? How to I get a Route to be activated inside of a class method?

import validator from './validator';

class Example {

  constructor(props) {
    super(props)
    this.saveAndContinue = thos.saveAndContinue.bind(this)
  }

  saveAndContinue () {
    var valid = validator.validate(this.props.form)
    if (valid) {
      axios.post('/path')
      <Redirect to='/other_tab'>
    } else {
      validator.showErrors()
    }
  }

  render() {
    <button onClick={this.saveAndContinue}>Save and Continue</button>
  }

}
like image 984
jaimefps Avatar asked Mar 08 '23 06:03

jaimefps


1 Answers

As discussed you should have access to the history object via this.props.history as described here.

If you look into the push function this will redirect you to any route you need. For example:

// Use push, replace, and go to navigate around.
this.props.history.push('/home', { some: 'state' })

https://reacttraining.com/react-router/web/api/history

like image 163
Purgatory Avatar answered Mar 18 '23 13:03

Purgatory