4

I have a React form which has the following form submission button:

<Link 
    className="btn btn-secondary btn-width-200 search-submit" 
    to={{pathname: '/booking/search', query: this.state.filters}}>
     Search

</Link>

In the above link I want to call a function handleSubmit(evt) on button click.

handleSubmit(evt) {
    evt.preventDefault();
    this.setState({form_submitted: true});
}

<Link className="btn btn-secondary btn-width-200 search-submit" to={{pathname: '/booking/search', query: this.state.filters}} onClick={this.handleSubmit.bind(this)}>Search</Link>

But the following ignores the to={{pathname: '/booking/search', query: this.state.filters}} and just takes handleSubmit function into consideration

Is there anyway to add to={{pathname: '/booking/search', query: this.state.filters}} to the handleSubmit function? Or is there anyway to resolve this issue?

laser
  • 1,388
  • 13
  • 14
anonn023432
  • 2,940
  • 6
  • 31
  • 63

3 Answers3

2

All you need to understand is, how to achieve route using react-router API. Basically you can configure it on two API, browserHistory and hashHistory. (link)

So, in otherword, by calling browserHistory.push('/booking/search') or hashHistory.push('/booking/search') you should be able to navigate between routes.

There is redux version also available, just in case if you want to manage your navigation via some action dispatch (though it is not necessary). Link

For more info: Programmatically navigate using react router

Community
  • 1
  • 1
Aman Gupta
  • 5,548
  • 10
  • 52
  • 88
2

This :

import {Link} from 'react-router';

handleSubmit(evt) {
    evt.preventDefault();
    this.setState({form_submitted: true});
}

<Link 
    className="btn btn-secondary btn-width-200 search-submit" 
    to={{pathname: '/booking/search', query: this.state.filters}}>
     Search

</Link>

Can be replaced by :

import {browserHistory} from 'react-router';

handleSubmit(evt) {
    evt.preventDefault();
    this.setState({form_submitted: true});
    return this.redirect('/booking/search', this.state.filters);

}

redirect(to, query) {
   browserHistory.push({pathname: to, query})

}

<a
    className="btn btn-secondary btn-width-200 search-submit" 
   onClick={this.handleSubmit} >
     Search

</a>
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
1

You can use the push router method in external Function instead of using Link. For example:

redirectFunction() {
 this.handleSubmit()
 router.push({
  to: '/booking/search',
  query: this.state.filters
 })
}

render () {
  <div 
   className="btn btn-secondary btn-width-200 search-submit" 
   onClick={this.redirectFunction.bind(this)}>
     Search 
  </div>
}
Robsonsjre
  • 1,586
  • 11
  • 17