. Advertisement .
..3..
. Advertisement .
..4..
When reading this article, you are probably looking for the answer to how to programmatically update query params in react-router. So let’s start with this article; you can refer to some methods we mentioned below, and we believe one of them is the one that you need.
What should we do to programmatically update query params in react-router?
Query parameters are one of a series of problems sent by the customer to the VPS. The server received these reports for processing and returned a matching engine along with the query submitted.
React-Router is a standard routing library in React that keeps the app’s interface in sync with the URL in the browser. React-Router allows you to route the “data flow” in your application explicitly. That means if you have this URL, it will be equivalent to this route and the corresponding interface.
Those are the basic concepts you can refer to before starting with the methods we give below.
Method 1: Assign query parameters
The first way you can try to update query params is to assign the query parameters in the push method of hashHistory, suppose like:
history.push({
pathname: '/dresses',
search: '?color=blue'
})
OR
history.push('/dresses?color=blue')
With this method, you can programmatically update query params in react-router
Method 2: The history.replace method
Besides the above method, you can also use the history.replace method. To call history.replace in the onchange function for navigation, you need to initialize the query string with the URLSearchParams constructor by the query string key name and value value.
import React from 'react';
import { useHistory, useLocation } from 'react-router';
const MyComponent = ()=>{
const history = useHistory();
const location = useLocation();
const onChange=(event)=>{
const {name, value} = event?.target;
const params = new URLSearchParams({[name]: value });
history.replace({ pathname: location.pathname, search: params.toString() });
}
return <input name="search" onChange={onChange} />
}
Method 3: Use hook useHistory
To use this method, you need to guarantee that you are using the component based on this component import function at the top
import {useHistory} from "react-router-dom"
And your component,
const history = useHistory()
history.push({
path-name: window.location.pathname,
search: '?color=blue'
})
Method 4: Use redux-thunk, react-router v4 and react-router-redux(5.0.0-alpha.6) package
This method can help users when using the search function can send the URL link for the same query to someone else, such as a fellow
import { push } from 'react-router-redux';
import qs from 'query-string';
export const search = () => (dispatch) => {
const query = { firstName: 'John', lastName: 'Doe' };
//API call to retrieve records
//...
const searchString = qs.stringify(query);
dispatch(push({
search: searchString
}))
}
Method 5: Produce the hook
To programmatically update query params in react-router, you can also try to produce your hook to simplify your work. You just need to visualize your URL like this:
/search?origin=home&page=1
function useUrl(param: string) {
const history = useHistory()
const { search, pathname } = useLocation()
const url = new URLSearchParams(search)
const urlParam = url.get(param)
const [value, setValue] = useState(urlParam !== null ? urlParam : '')
function _setValue(val: string){
url.set(param, val)
history.replace({ pathname, search: url.toString() });
setValue(val)
}
return [value, _setValue]
}
Actual usage:
function SearchPage() {
const [origin] = useUrl("origin")
const [page, setPage] = useUrl("page")
return (
<div>
<p>Return to: {origin}</p>
<p>Current Page: {page}</p>
</div>
)
}
Method 6: For users of react-router v4.3
This method applies to react-router v4.3. If you are using react-router v4.3, you can try it to update query params
const addQuery = (key, value) => {
let pathname = props.location.pathname;
// returns path: '/app/books'
let searchParams = new URLSearchParams(props.location.search);
// returns the existing query string: '?type=fiction&author=fahid'
searchParams.set(key, value);
this.props.history.push({
pathname: pathname,
search: searchParams.toString()
});
};
const removeQuery = (key) => {
let pathname = props.location.pathname;
// returns path: '/app/books'
let searchParams = new URLSearchParams(props.location.search);
// returns the existing query string: '?type=fiction&author=fahid'
searchParams.delete(key);
this.props.history.push({
pathname: pathname,
search: searchParams.toString()
});
};
function SomeComponent({ location }) {
return <div>
<button onClick={ () => addQuery('book', 'react')}>search react books</button>
<button onClick={ () => removeQuery('book')}>remove search</button>
</div>;
}
Conclusion
The above are methods that you can try to programmatically update query params in react-router. And If you find them useful or you have any suggestions, don’t hesitate to write them down in the comments section. Thank you for taking the time to read this article, good luck!
Read more:
→ Solutions For The Error “Error: request.query has been replaced by request.url.searchParams in npm”
Leave a comment