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)