Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4 <Link> for Form

How can I use <Link> with a <form>? I am trying to avoid programatic routing as I see many warnings against it.

Form has two fields:

<form>
    <input type="text" id="what"/>
    <input type="text" id="where"/>
    <Link><button type="submit"></Link>
</form>

My goal is to send the page to '/' + document.getElementById('where').value + '/' + document.getElementById('what').value, is it possible with v4 router?

like image 368
Noitidart Avatar asked Feb 06 '17 05:02

Noitidart


1 Answers

With v4, the <Link> is only used to create <a> elements.

I think that most warnings against programmatic navigation come from people not really understanding how history works, especially when attempting to do it outside of components. The withRouter HOC provides an easy way to add routing to a component.

Additionally, I would do the routing from within a form component instead of from the button. Then, you just need to make sure that the button's type is submit (which is the default).

You are also using DOM functions to access the values in your code. I would recommend instead using controlled inputs, but that is obviously up to you.

class NavForm extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      what: '',
      where: ''
    }

    this.submitHandler = this.submitHandler.bind(this)
    this.handleInput = this.handleInput.bind(this)
  }

  handleInput(event) {
    const target = event.target
    this.setState({
      [target.name]: target.value
    })
  }  

  submitHandler(event) {
    event.preventDefault()
    // do some sort of verification here if you need to
    this.props.push(`${this.state.where}/${this.state.what}`)
  }

  render() {
    return (
      <form onSubmit={this.submitHandler}>
        <input
          type='text'
          name='what'
          value={this.state.what}
          onChange={this.handleInput} />
        <input
          type='text'
          name='where'
          value={this.state.where}
          onChange={this.handleInput} />
        <button>Submit</button>
      </form>
    )
  }
}

export default withRouter(NavForm)
like image 139
Paul S Avatar answered Nov 09 '22 14:11

Paul S