Seth McClaine
Seth McClaine

Reputation: 10040

How to remove query param with react hooks?

I know we can replace query params in component based classes doing something along the lines of:

  componentDidMount() {       
    const { location, replace } = this.props;   

    const queryParams = new URLSearchParams(location.search);   
    if (queryParams.has('error')) { 
      this.setError(    
        'There was a problem.'  
      );    
      queryParams.delete('error');  
      replace({ 
        search: queryParams.toString(), 
      });   
    }   
  }

Is there a way to do it with react hooks in a functional component?

Upvotes: 56

Views: 121770

Answers (2)

Ajeet Shah
Ajeet Shah

Reputation: 19823

For React Router V6 and above, see the answer below.


Original Answer:

Yes, you can use useHistory & useLocation hooks from react-router:


import React, { useState, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'

export default function Foo() {
  const [error, setError] = useState('')

  const location = useLocation()
  const history = useHistory()

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search)
    
    if (queryParams.has('error')) {
      setError('There was a problem.')
      queryParams.delete('error')
      history.replace({
        search: queryParams.toString(),
      })
    }
  }, [])

  return (
    <>Component</>
  )
}

As useHistory() returns history object which has replace function which can be used to replace the current entry on the history stack.

And useLocation() returns location object which has search property containing the URL query string e.g. ?error=occurred&foo=bar" which can be converted into object using URLSearchParams API (which is not supported in IE).

Upvotes: 82

Vaelyr
Vaelyr

Reputation: 3176

Use useSearchParams hook.

import {useSearchParams} from 'react-router-dom';

export const App =() => {
  const [searchParams, setSearchParams] = useSearchParams();

  const removeErrorParam = () => {
    if (searchParams.has('error')) {
      searchParams.delete('error');
      setSearchParams(searchParams);
    }
  }

  return <button onClick={removeErrorParam}>Remove error param</button>
}

Upvotes: 46

Related Questions