When I use a <Link />
component, navigation happens smoothly without page refresh, but when I try to navigate through history.push()
(ie on form submission), the page refreshes. How do I prevent history.push()
from doing a refresh? Here's my code:
import React from 'react';
import {withRouter} from 'react-router-dom';
import qs from 'query-string';
class SearchBox extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({value: e.target.value});
}
handleSubmit(e) {
this.props.history.push('?' + qs.stringify({search: this.state.value}));
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="searchbox">
<input
type="text"
name="search"
value={this.state.value}
onChange={this.handleChange}
placeholder="Search..."
/>
</div>
</form>
);
}
}
export default withRouter(SearchBox);
You can use this code
import { createBrowserHistory } from "history";
// ... Your codes
handleSubmit(e) {
const historyBrowser = createBrowserHistory({
basename: process.env.PUBLIC_URL,
forceRefresh: false,
});
historyBrowser.push('?' + qs.stringify({search: this.state.value}));
e.preventDefault();
}
If you set forceRefresh: true
page will refresh.
Make e.preventDefault()
the first statement in the handleSubmit()
function and then push the url
to history.
Based on the comment of @ic3b3rg: Had to include a path in the argument for push
:
handleSubmit(e) {
this.props.history.push('/?' + qs.stringify({search: this.state.value}));
e.preventDefault();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.