简体   繁体   中英

OnClick event handler redirect to in reactjs?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM