Reputation: 375
constructor(props){
super(props);
this.state = { term: '' };
this.onInputChange = this.onInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onInputChange(event){
this.setState({term: event.target.value});
this.props.handle_search(event.target.value)
}
onFormSubmit(event){
event.preventDefault();
this.setState({ term: '' });
}
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Search games..."
className="form-control"
value={this.state.term}
onChange={this.onInputChange}
/>
<span className="input-group-btn">
<button type="submit" className="btn btn-secondary">
<NavLink to='/game_search' style={{ textDecoration: 'none' }}> Search </NavLink>
</button>
</span>
</form>
I am building a search bar with a search button. I am trying to redirect to another page after the user finish typing in the search bar and press the search button or the "Enter key". Redux keeps the token the user typed so that on the page it redirects to it can call the API with that token stored in Redux.
The problem I am having right now is that when I press the "Enter key" after I type something in the search bar, it does not redirects to the next page. It works perfectly fine when I click the search button since I put a Navlink in the button tag.
I have tried put the
this.props.history.push("/game_search") //game search is the page it redirects to
and the
window.open("/game_search");
window.location.href("/game_search");
into the onFormSubmit method to force it to redirect to the next page, but it refreshes the page and does not keep the data in redux.
Is there any way I can redirects to the other page with the "Enter key" while keeping the data? Thanks in advance.
Upvotes: 0
Views: 2529
Reputation: 3907
I guess you are using react-router-dom
(because I see NavLink
component from that package).
So you actually can use this.props.history.push("/game_search")
method but you have to include React Router's props within your SearchBar (or whatever) component using HOC withRouter
:
import { withRouter } from 'react-router-dom';
class SearchBar extends React.Component { .... }
export default withRouter(SearchBar);
withRouter
higher-order component will add both history
and match
Router's props to passed component.
Upvotes: 2