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?
First you'll need to import the useSearchParams hook and destruct the return value to get the current value of, React Router v6 calls these the “search params” due to them existing on the window.
The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.
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).
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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With