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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With