How To Navigate Via ClickHandlers?
I just started learning React and I'm stuck in the following scenario. There is an input field and on clicking the search button it takes the input value and redirect to /search/se
Solution 1:
I'm gonna make the assumption that you're not building a single page app and using something along the lines of React router. And that what you need to do is simply navigate to a url based on the input.
There are two main ways of doing depending on wether you want to:
- Style an
<a>
as your button:
var Component = React.createClass({
getInitialState: function() { return {query: ''} },
queryChange: function(evt) {
this.setState({query: evt.target.value});
},
_buildLinkHref: function() {
return '/search/'+this.state.query+'/some-action';
},
render: function() {
return (
<div className="component-wrapper">
<input type="text" value={this.state.query} />
<a href={this._buildLinkHref()} className="button">
Search
</a>
</div>
);
}
});
This way you're keeping the query (value of the input) in the state. And whenever the input changes is automatically changes the href of the link.
- Use a
<button>
and redirect programatically:
var Component = React.createClass({
getInitialState: function() { return {query: ''} },
queryChange: function(evt) {
this.setState({query: evt.target.value});
},
handleSearch: function() {
window.location = '/search/'+this.state.query+'/some-action';
},
render: function() {
return (
<div className="component-wrapper">
<input type="text" value={this.state.query} />
<button onClick={this.handleSearch()} className="button">
Search
</button>
</div>
);
}
});
This way you handle the redirect programatically by setting your desired location to window.location
.
Solution 2:
Adding on from the existing answer may need to bind your function like so:
constructor(props) {
super(props);
this.handleSearch = this.handleSearch.bind(this);
}
Post a Comment for "How To Navigate Via ClickHandlers?"