React router rendering twice and URL changes by dropping all query parameters

gaganbm

I am using BrowserRouter and history.push to navigate between pages. I want to traverse to a new page with query parameters entered in the first page.

i.e., in the homepage, there is a search bar where user enters some search string abc, and when the button is clicked, I want to redirect to another page /search?q=abc

What I observed is, the /search?q=abc is rendered properly once and then it automatically redirects to /search? dropping all the query parameters. I am not able to understand why is it rendering twice?

Packages

"react": "^16.12.0",
"react-bootstrap": "^1.0.0-beta.16",
"react-dom": "^16.12.0",
"react-router-dom": "^5.1.2",

App.js

import React, { Component}  from 'react';
import './App.css';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Jumbotron from "./component/Jumbotron";

const SearchPage = ({ match, location }) => {
  return (
      <p>
        <strong>Query Params: </strong>
        {location.search}
      </p>
  );
};

const HomePage = () => {
  return (
      <div className="d-flex flex-column">
        <div className="container-fluid">
          <Jumbotron/>
        </div>
      </div>
  )
};

class App extends Component {
  render() {
    return (
        <Router>
          <Route exact={true} path='/' render={HomePage}/>
          <Route exact path="/search" render={SearchPage} />
        </Router>
    );
  }
}

export default App;

Jumbotron.jsx <- this is the first page containing search bar

import React, { Component } from 'react';
import { withRouter } from 'react-router';
import history from "../utils/history";

class Jumbotron extends Component {

    handleSubmit = () => {
        history.push({
            pathname: '/search',
            search: '?q=' + this.state.query
        })
    };

    handleChange = e => {
        this.setState({query: e.target.value});
        console.log(e.target.value)
    };

    render() {
        return (<>
            <div className="d-flex jumbotron">
                <div className="align-self-center container mx-auto">
                    <br/>
                    <div>

                    </div>
                    <div className="align-self-center">
                        <form className="d-flex justify-content-center form-inline my-2 my-lg-0">
                            <input className="search-input col-md-6  mb-3 form-control"
                                   type="search"
                                   placeholder="Type the address here"
                                   aria-label="Search"
                                   onChange={this.handleChange}
                            />
                            <button className="search-btn col-md-1 mb-3 btn btn-primary"
                                    onClick={this.handleSubmit}>Search
                            </button>

                        </form>
                    </div>
                </div>
            </div>
            </>
        )
    }
}

export default withRouter(Jumbotron);

history.js

import { createBrowserHistory } from "history";
export default createBrowserHistory();

What am I missing here?

UPDATE

Here is an example with the above code that depicts the behavior: https://codesandbox.io/s/blissful-fermat-60xzy

gdh

2 ways to solve your issue:

First solution:

  • import Router not BrowserRouter
  • pass your history that you have defined in ./history.js to the Router. Like this <Router history={history}>
  • Now history.push({..... should work as you expected.

Second solution:

  • import BrowserRouter
  • wrap the Jumbotron component with withRouter
  • use this.props.history.push(...) instead of history.push(...)

Working copy of your code(1st solution) is here:

https://codesandbox.io/s/router-issue-page-refresh-after-search-hl849?file=/src/App.js

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Preserve query parameters in react-router

分類Dev

server fall back and nested routes with react-router and url parameters

分類Dev

React Router not rendering component initially

分類Dev

Router changes the url but not the components rendered

分類Dev

React Component not rendering on using react router 4

分類Dev

Problem rendering Component in a different page with React Router

分類Dev

React Router only rendering one route

分類Dev

React Router 4 - Issues Rendering Nested Link

分類Dev

Nested component in react-router is not rendering

分類Dev

301 redirect with query parameters and ~ in URL

分類Dev

React Router Without Changing URL

分類Dev

How to avoid redirecting twice (react-router-redux)?

分類Dev

React router nested routes. Not rendering child routes

分類Dev

React-Router - Route re-rendering component on route change

分類Dev

UI-router: how to show a state twice in a page with different parameters and sub-states

分類Dev

SpringMVC: URL parameter after query parameters

分類Dev

How do I get query parameters in the URL

分類Dev

Regex for URL rewrite with optional query string parameters

分類Dev

RewriteRule required for URL's with 2 query parameters

分類Dev

Angularjs URL parmeters gets passed as Query Parameters

分類Dev

react-router setRouteLeaveHook still updating URL

分類Dev

React Router URL Throws Error With Parameter

分類Dev

ReactJS - React Router not changing component but url is changing

分類Dev

Send different router in app.use() based on URL parameters

分類Dev

Parameters in URL using Angular's UI-Router, issue with .otherwise

分類Dev

Router Resolver not rendering component

分類Dev

Server Side Rendering with React/Redux, getting url params to pass into loadData

分類Dev

Select changes selected only twice

分類Dev

Prevent rendering of a particular layout when on a specific route with react router dom v4?

Related 関連記事

  1. 1

    Preserve query parameters in react-router

  2. 2

    server fall back and nested routes with react-router and url parameters

  3. 3

    React Router not rendering component initially

  4. 4

    Router changes the url but not the components rendered

  5. 5

    React Component not rendering on using react router 4

  6. 6

    Problem rendering Component in a different page with React Router

  7. 7

    React Router only rendering one route

  8. 8

    React Router 4 - Issues Rendering Nested Link

  9. 9

    Nested component in react-router is not rendering

  10. 10

    301 redirect with query parameters and ~ in URL

  11. 11

    React Router Without Changing URL

  12. 12

    How to avoid redirecting twice (react-router-redux)?

  13. 13

    React router nested routes. Not rendering child routes

  14. 14

    React-Router - Route re-rendering component on route change

  15. 15

    UI-router: how to show a state twice in a page with different parameters and sub-states

  16. 16

    SpringMVC: URL parameter after query parameters

  17. 17

    How do I get query parameters in the URL

  18. 18

    Regex for URL rewrite with optional query string parameters

  19. 19

    RewriteRule required for URL's with 2 query parameters

  20. 20

    Angularjs URL parmeters gets passed as Query Parameters

  21. 21

    react-router setRouteLeaveHook still updating URL

  22. 22

    React Router URL Throws Error With Parameter

  23. 23

    ReactJS - React Router not changing component but url is changing

  24. 24

    Send different router in app.use() based on URL parameters

  25. 25

    Parameters in URL using Angular's UI-Router, issue with .otherwise

  26. 26

    Router Resolver not rendering component

  27. 27

    Server Side Rendering with React/Redux, getting url params to pass into loadData

  28. 28

    Select changes selected only twice

  29. 29

    Prevent rendering of a particular layout when on a specific route with react router dom v4?

ホットタグ

アーカイブ