Search code examples
javascriptreactjsreact-routerquery-stringreact-class-based-component

query-string in react router v6


I show two query strings in my URL like this **localhost3000/?filter=all&search=something** but the problem is when there isn't anything for search my URL still shows **localhost3000/?filter=all&search=** while I want to show search if it uses and when there is no search it shows **localhost3000/?filter=all** this is my code:

  replaceUrl = () => {
    const x = {
      filter: this.state.filter,
      search: this.state.searchterm,
    };
    const y = queryString.stringify(x);
    this.props.navigate(`?${y}`);
  };

replaceUrl calls when filter changes or something search


Solution

  • Just set the search field if the this.state.searchterm exist

    replaceUrl = () => {
        const x = {
          filter: this.state.filter,
        };
    
        if (this.state.searchterm) x.search = this.state.searchterm;
    
        const y = queryString.stringify(x);
    
        this.props.navigate(`?${y}`);
      };