How to pass object to another screen via window.open - reactjs

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

Related

Redirecting to a specific page based on conditions (Ionic + React)

I have made a questionnaire using ionic slides and I am able to create an array called Answers which stores the selected value from each question.
I wanted to enquire how I can now use an if-statement with this array and then navigate to a specific page when I click "Finish" on the last question?
const answers = [selected1, selected2, selected3, selected4, selected5];
const s1 = [1,2,1,1,1];
function suggestion(answers: number[] | undefined): void {
if (answers == s1) {
**not sure what to do here to navigate**
}
}
This is the IonButton code:
<IonButton class = "finishbttn" size="small" onClick = {()=> suggestion(answers)}> Finish </IonButton>
If you want a link to a page, you should use routerLink instead of onClick(). onClick() is for doing processing (submitting a form, toggling a value, etc.), while routerLink is to link to another page in the router.
Although it is possible to do a redirect in onClick(), IonRouter can get confused, so it is better to use routerLink.
So, first change your <IonButton> to use routerLink.
<IonButton routerLink={doRedirect(answerValue)}>Finish</IonButton>
This uses a redirect function, so you redirect based on the answer values:
const doRedirect = (answers: number[] | undefined) => {
if (answers === s1) {
return 'routeForS1';
}
}
You will of course need to create the routes in your router so that the redirects will work.

Changing an input parameter within React component

I am going through the code of a project and I see the following code:
export const FileLink = React.memo(({ url, data, ext, linkContent }) => {
...
...
if (!url.includes('?')) {
url += '?'
}
if (!url.endsWith('?')) {
url += '&'
}
return <a href={`${url}file_format=${ext}`}>{linkContent}</a>
})
It is working fine and no bugs appear in app behavior. But url is a passed parameter and it is changed within the FileLink: from what I read React components should be pure functions. So, I wonder whether its ok to do that, under which circumstances, and if not - why? What can go wrong? Any examples of how it could mess up the app?
(If interested to see the full code: https://github.com/broadinstitute/seqr/blob/8b4419285dfac9365c5c500bbb87b89808c0cedd/ui/shared/components/buttons/ExportTableButton.jsx#L37)
url is a local variable. Reassigning that variable, which is all this code is doing to it, has no possibility of affecting code outside of this function call. It doesn't make the function impure.
Now, if you were passed in an object, and you started mutating that object, then that would break purity. Because if the component that passed you this object is still using it, then it can "see" that change. For example:
const Example = ({ someObjectProp }) => {
someObjectProp.name = 'bob';
}

Updating url in GeoJSONLayer using ArcGIS JS API

I am working on a simple node/react application that allows for the the request of data using the url parameter in GeoJSONLayer. The way that I set up the api I need to be able to change the url to get a new set of data. I have set up a useEffect() to load the map that has all of the map elements and have told it to listen for changes on the treeURL.
const [treeURL, setTreeURL] = TreeURL();
useEffect(async()=>{
loadMap(treeURL)
},[treeURL]);
The TreeURL function is just a simple useState() to default to getAll which is the default way of getting all of the data back. This part is working fine the map renders with the data that is fetched.
const TreeURL = () => {
const getAll = 'getAll'
const [treeURL, setTreeUrl] = useState(getAll)
return [treeURL, setTreeUrl]
}
When I go to update the data using the setTreeURL() the function runs. treeURL prints out into the console, but useEffect() is not called and the map does not update.
props.list.forEach((item) => {
elements.push(
<li class="mr-3">
<button
key={item}
className="inline-block border border-blue-500 rounded py-1 px-3 bg-blue-500 text-white"
onClick={()=>{
setTreeURL(`getByParams?CONDITION=${item}`)
console.log(treeURL)
}
}>{item}
</button>
</li>)
})
How do I update GeoJSONLayer's URL once the map has been loaded?
While its a little difficult to answer the question without more context regarding what you'd like to achieve by updating the GeoJSON's URL, there are a couple ways I could see you accomplishing this based on how the URL is updated.
If you are trying to query the initial GeoJSON source by adding URL parameters, you might be able to use the customParameters property of a GeoJSON and use the refresh() property to fetch new data. You can check out an example of this in action provided by Esri here.
However, if you are look to load an entirely new GeoJSON, than you might have to resort to creating a new GeoJSON object with the specified URL. You can also accomplish this by reading in your GeoJSON as a blob, as seen in this code snippet below and further explained in this ArcGIS blog article.
const blob = new Blob([JSON.stringify(geojson)], {type: "application/json"});
const url = URL.createObjectURL(blob);
const layer = new GeoJSONLayer({ url });

How to update query param in url in React?

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}`)

Angular2 How can I get destination URL in a Guard?

I am trying to create a CanDeactivate guard, to prompt "save changes" to the user when he navigates away from the route. There are some routes that I would like to exclude (lets say when user switches tabs, but doesnt choose a new item). I've been really struggling in understanding how can I get the destination URL without using some sort of navigation service and just keep the full URL there. Here is my signature for can deactivate
// This is what handles the deactivate
public canDeactivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
All of the 'route' and 'state' object contain the previous URL and no information about the destination URL.
I trigger the navigation in another component with
this._router.navigate(['/clients', this.selectedClient.id, page]);
Actually destination state is one of the parameter of CanDeactivate.
canDeactivate(
component: CanComponentDeactivate,
route: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
return true;
}
Reference: https://angular.io/api/router/CanDeactivate
You can subscribe to the router's events:
NavigationStart should fire before CanDeactivate, so you can grab the destination.
routingDestination: string = "";
constructor(router:Router) {
router
.events
.filter(e:Event => e instanceof NavigationStart)
.subscribe((e: NavigationStart) => this.routingDestination = e.url)
}
}
That aside, I think needing to know the destination in CanDeactivate is kind of a design flaw. But as I don't know your app, this might actually be the right way.

Resources