Reputation: 310
I have passed props through to different components and pages before but this has been through link or just added these to the component tag itself.
The issue I have here is that the redirect is not going through a link tag or in a component tag and instead I am simply using window.locatio.href ="whatever the url is".
I simply want to pass a variable through to this (I am technically doing a refresh in this situation so window.location.reload() could also work if it is possible).
How would I pass through a variable within this. When using express you can do fetch statements with an endpoint simialr to (might not be exact syntax) "./page${variableYouWant}" Then access sit in the express file using req.params.variableYouWant.
Is this possible to pass a variable this way and how would I then access it.
Here is the most important snippet of my code.
pageRelocator(mssg) {
if (mssg.length < 35) {
toast.info(`${mssg}`, {
draggable: true,
autoClose: 1500
});
window.location.href = "http://localhost:3000/completed-assessment";
} else if (mssg.length > 35) {
toast.error(`${mssg}`, {
draggable: true,
autoClose: 1500
});
//Here I would like to pass a variable
window.location.href = "http://localhost:3000/user-questions";
}
}
EDIT--
componentDidMount() {
const search = this.props.location.mssg;
alert(search); // returns the URL query String
const params = new URLSearchParams(search);
const IdFromURL = params.get("mssg");
this.setState({
questions: this.getItems(),
WorkStations: this.getWorkStations()
});
}
pageRelocator(mssg) {
if (mssg.length < 35) {
window.location.href = "http://localhost:3000/completed-assessment";
} else if (mssg.length > 35) {
window.location.href = `http://localhost:3000/user-questions?mssg=${mssg}`;
}
}
Upvotes: 1
Views: 8845
Reputation: 1661
Try using the URLSearchParams
which defines utility methods to work with the query string of URL.so to attach a variable you would do
var id=5;
window.location.href = `http://localhost:3000/user-questions?id=${id}`;
and to retreive id from the URL you would do
const search = props.location.search; // returns the URL query String
const params = new URLSearchParams(search);
const IdFromURL = params.get('id');
Hope this helps
Upvotes: 7
Reputation: 274
If you want the data to be present even after refresh, try to pass the variable in params.
http://localhost:3000/completed-assessment?your_variable=value
If you want to use this params value you can use
window.location.search
Using URLSearchParams
you can get the each params you've sent with the URL.
Please refer https://www.sitepoint.com/get-url-parameters-with-javascript/ for more info
Upvotes: 0