Dmitry Shvedov
Dmitry Shvedov

Reputation: 3296

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);

Upvotes: 4

Views: 4539

Answers (3)

Dmitry Shvedov
Dmitry Shvedov

Reputation: 3296

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

Upvotes: 0

Medisa
Medisa

Reputation: 409

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.

Upvotes: 1

maya_nk99
maya_nk99

Reputation: 502

Make e.preventDefault() the first statement in the handleSubmit() function and then push the url to history.

Upvotes: 0

Related Questions