Erik Nijland
Erik Nijland

Reputation: 1199

Use <Redirect> component to update search param on the current page

I want to update a single search parameter in the URL when submitting a form. Being new to React and react-router I want to give the <Redirect> component a chance even though my instinct says to just update the URL with regular JavaScript.

The initial redirect is working as expected. But follow-up redirects are happening as soon as the query changes. I only want redirects to happen when pressing submit.

export default function SearchForm () {
  const [ inputQuery, setInputQuery ] = useState<string>(useSearch('query') || '');
  const [ redirect, setRedirect ] = useState(false);

  function search (event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();

    setRedirect(true);
  }

  return (
    <div>
      <form onSubmit={search}>
        <label>
          Search query
          <input value={inputQuery} onChange={(event) => setInputQuery(event.target.value)} autoFocus />
        </label>

        <button type="submit">Search</button>
      </form>

      {redirect &&
        <Redirect to={`?query=${inputQuery}`} />
      }
    </div>
  );
}

Upvotes: 1

Views: 69

Answers (1)

Blake
Blake

Reputation: 299

Is there a reason you have your Redirect component being returned with your form? If you want to redirect on submit, I would use withRouter from react router, and then call its history.push();

  function search (event: React.FormEvent<HTMLFormElement>) {
    props.history.push({pathname: '/whatever-page', search: '?query=' + inputQuery})
  }

  return (
    <div>
      <form onSubmit={search}>
        <label>
          Search query
          <input value={inputQuery} onChange={(event) => setInputQuery(event.target.value)} autoFocus />
        </label>

        <button type="submit">Search</button>
      </form>
    </div>
  );

export default withRouter(SearchForm);

Upvotes: 1

Related Questions