0

I need to have the user edit the url the "path" appears in the input of the other component and when searching the input change the url in real time. How can I use "withRouter" to perform this function?

// App.js component

    class App extends Component {

      render() {
        const { match, location, history } = this.props;

        return (
          <div >
              <Search
                searchString={location.pathname}
              />
          </div>
        )
      }
    }

    export default withRouter(App)

//Search.js component  

    const Search = ({ searchString }) => (
            <div>
                <input
                    value={searchString} 
                    type="search"
                    placeholder="Search"
                    aria-label="Search"
                />
            </div>
    )
Mario Rodeghiero
  • 248
  • 1
  • 3
  • 15

1 Answers1

0

This should work for you although I'm not sure redirecting user to another page while typing into search input is a good UX.

// App.js component

    class App extends Component {
      state = {
        searchString: this.props.location.pathname
      }

      handleSearch = (event) => {
        this.setState(
          { searchString: event.target.value },
          () => this.props.history.push('/search?query=' + this.state.searchString)
        );
      }

      render() {
        return (
          <div >
              <Search
                onChange={this.handleSearch}
                searchString={this.state.searchString}
              />
          </div>
        )
      }
    }

    export default withRouter(App)


    const Search = ({ searchString, onChange }) => (
            <div>
                <input
                    onChange={onChange}
                    value={searchString} 
                    type="search"
                    placeholder="Search"
                    aria-label="Search"
                />
            </div>
    )

Václav Zeman
  • 606
  • 7
  • 21