Search code examples
javascriptreactjsreact-routerreact-router-v4history

React-router - navigating through history.push() refreshes the page


When I use a <Link /> component, navigation happens smoothly without page refresh, but when I try to navigate through history.push() (i.e. 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);

Solution

  • 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();
      }