How to update query param in url in React? - reactjs

I am trying to create pagination in my web application using react-js-pagination. Pagination is showing in webpage but i want to change page param inside url according to page number like &page=4. I tried to use
this.props.history.push(`${window.location.search}&page=${pageNumber}`)
but this is appending &page=4 everytime i click on pagination link. I know this wrong way to update url. How can i update only page parameter according to pageNumber in url?
handlePageChange = (pageNumber) => {
this.setState({activePage: pageNumber});
this.props.history.push(`${window.location.search}&page=${pageNumber}`)
}
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={10}
totalItemsCount={100}
onChange={this.handlePageChange}
/>

You could use location.pathname instead of location.search but all the other query parameters will also be deleted.
So if you have other parameters that you need and you only want to change the page parameter, you can use the URLSearchParams javascript object which will make it easier to replace the current pagination.
So do as follows:
Create a new variable which contains the current url with all the params:
let currentUrlParams = new URLSearchParams(window.location.search);
Then change the page parameter to the value you need in that variable:
currentUrlParams.set('page', pageNumber);
Now push the current url with the new params using history.push:
this.props.history.push(window.location.pathname + "?" + currentUrlParams.toString());
So the full code will be:
let currentUrlParams = new URLSearchParams(window.location.search);
currentUrlParams.set('page', pageNumber);
this.props.history.push(window.location.pathname + "?" + currentUrlParams.toString());

I think you should use pathname instead of search:
this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)

Related

How to pass object to another screen via window.open

I have the following problem: I can't pass values to get to the other screen.
I have the following code that should pass an object to be received on the destination screen and I also don't know how to receive it on the destination
I want object = {a:121, b: 232} to be sent to the other screen
function openInNewTab(url: string | URL | undefined) {
const params = `scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,width=300,height=300`;
var win = window.open(url,'_blank', params)!;
win.focus();
}
<button id='btn' onClick={() => openInNewTab("../printer")}>abrir</button>
You can pass it to query params, but is a not most best idea.
window.open(`${url}?obj=${JSON.stringify(yourObject)}`)
But better, I can advise you to use some router library, for ex.
react-router-dom

How to send MULTIPLE params with useHistory hook in React?

history.push({pathname: '/search?', state: {param1: 'value1'}}) this doesn't work. It just redirects to /search
history.push('/search?', {param1: 'value1'}) this doesn't work.
history.push('/search?', ['param1=value1']) this doesn't work.
history.push('/search?', [... 'param1=value1']) this doesn't work.
history.push('/search?', state: {param1: 'value1'}) this doesn't work.
The only thing that works is this: history.push('/search?param1=value1').
But I need to dynamically send multiple params. How do I do that? The official documentation shows the first example with an object, but it's not working for me. I am using functional components by the way.
If I understand your question correctly you want to dynamically get/set the queryString parameters of the URL.
None of the examples you've shared work because the second argument to history.push is route state.
history.push(path|To, [state])
Trying to pass queryString parameters in the second argument doesn't work.
Use URLSearchParams to construct a searchParams object that you can then update the params of, to be used in the history.push method. This method persists any existing queryString parameters.
Example:
const { search } = useLocation();
...
// get the search params for the current location
const searchParams = new URLSearchParams(search);
// update params as necessary, i.e. set/delete
searchParams.set("param1", "value1");
searchParams.set("param2", "value2");
searchParams.set("param3", "value3");
// push new route using to object
history.push({
pathname: "/search",
search: searchParams.toString(),
});
OFC, if you don't need this level of control and just need to inject the three dynamic values you could just use a template string.
history.push(`/search?param1=${value1}&param2=${value2}&param3=${value3}`);
How about this?
history.push('/search?param1=value1&param2=value2')

How to make onClick to trigger a download a video/photo given a download url?

If I have an array of data
for example
["download_url": "example.com/url/23131" ...]
and in the return function of the react rendering, how can you make onClick of a button to make user trigger the download of the download_url ?
Thanks
This is how I do it. Pass your url into that function
export const downloadFile = url => window.location.assign(url, '_blank');
Assuming this is your object:
let obj = { "download_url": "example.com/url/23131",
.... };
This ideally should be an anchor tag.
<a download href={obj["download_url"]}>Download</a>
This is more semantically correct than using a button to trigger a download. anchor tags are for resources and you are redirecting the user to a new resource.
The provision of download attribute is a good indication as to how HTML wants us to implement it.

React - history.push is not working- when only query is changed

I have URL like :http://localhost:8000/main/target/:targetId/id/d:id?query=x,y
On an action I need to update url and that am doing using history.push.
now I have two scenarios and one is working other one is not :
first and working scenario- if history.push tries to update url with new value for :targetId or :id along with url query - then url gets updated and rerendering happens. Things works for me
second and not working scenario - if :targeted and:id in url remains same and I just try to change the query- url doesnt get updated using history.push.
Need to handle the second scenario and want to update url and update components based on updated url.
I have one action to update url on click:
const onElClick = e => {
const targetId = e.target;
const id= e.id;
const query = `${e.name},${e.color}`
history.push(
`/main/target/${targetId}/id/${id}?query=${query}`
);
};
And on the target page, I'm using useEffect to capture the change:
useEffect(()=> {
....
}, [window.location.search]);

React router keep query params when changing route and back

I have a website with different pages based on react-router v4. Each page have url query based filters it means filter setting are stored on url like mysite.com/page1?filterKey=value.
My goal is to keep filter values on query when user back from another page ( mysite.com/page2).
The only 2 ways I see is either to use redux as Will Jenkins suggested, or to set the state in the parent container (either App.js, or the file handling your routes) :
In the parent container, define the function
setQuery = query => this.setState({query})
Pass the function to the child component
In the child component, pass the query on componentDidMount :
componentDidMount (){
this.setQuery( decodeURIComponent(querySearch(this.props.location.search).param) )
}
I found other one solutions using react hooks based global state:
const [podcastsUrlSearch, updateGlobalState] = useGlobalState('podcastsUrlSerach')
useLayoutEffect(() => {
if (!isEqual(props.location.search, podcastsUrlSearch)) {
updateGlobalState(props.location.search)
}
if (podcastsUrlSearch) {
props.history.replace({ ...props.history.location, search: podcastsUrlSearch })
}
}, [])
useLayoutEffect(() => {
updateGlobalState(props.location.search)
}, [props.location.search])
For example using a dropdown as a filter
use -->localStorage.setItem("companyDrpDwnValue")
on onChange event
and call the the below method to intialize the param on ComponentDidMount ,with which you were filtering the table
and filter the array with the filter param to get your filtered array

Resources