0

I'm reading a lot and trying to digest how to redirect with withRouter and all. But I read at some place that onClick the page should be redirected to specified link. Other thing is that in react-router latest version history.push() is not working then how to use that with latest version of react-router. I also read a question on stack overflow but it's not giving any concrete solution.

Here is code a basic simple but didn't able to get in official docs as well.

If I have a form and on submit button page should be redirected to a link, I tried to do with history.push() but as official docs suggest that it's not working. How can I achieve that?

Here is code:

import React,{Component} from "react";
import {BrowserRouter as Router, Link, Switch, Route} from "react-router-dom";
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      firstName:'',
    };
  }
  inputData = event => {
    this.setState({
      [event.target.name]:event.target.value
    });
  }

  render(){
    return(
      <div>
        <form>
          firstName
          <input type="text" name="firstName" onChange={this.inputData}/>
          <button type="submit" onClick={}></button>
        </form>
      </div>
    );
  }
}
export default App;

What should I write in on click event that it will redirect me to new page?

3
  • Can you give solution in code with history if it's possible?? Commented Mar 31, 2018 at 17:43
  • official docs suggest that it's not working could you point where? Commented Mar 31, 2018 at 17:45
  • 1
    you've imported BrowserRouter.. but you're not using it anywhere Commented Mar 31, 2018 at 17:54

1 Answer 1

3

For the simple answer, you can use Link component from react-router, instead of button.

<span className="input-group-btn">
  <Link to="/register" />Click to Register</Link>
</span>

If you using react-router v2.8.1 then try to implement Router redirect.

import { Router } from 'react-router';

export default class Foo extends Component {

  static get contextTypes() {
    return {
      router: React.PropTypes.object.isRequired,
    };
  }

  handleClick() {
    this.context.router.push('/some-path');
  }
}

I hope this the above two option solve your issue.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.