+ 1
How to make the url to change dinamically when redirecting on click in react?
I need to make the url to change dinamically, so i can use it in different cards. my code: return ( proops.new.map((content, index) => <NewsCard key={index} title={content.title} onClick={()=>{ location.href = 'www.example.com/?a=queryString'; ) If someone know how to change the url and the query string dinamically pls help me i am new in React Typescript.
7 Answers
+ 3
Comment out everything in the map function and just see what each queryString looks like:
console.log(content.queryString)
Is it what you expect? I.e. is it a string, not undefined or anything else?
If it is, then maybe it's just a TypeScript issue. Sounds like it could be because you refer to 'any'.
Also, need to use backticks like I showed in the first answer, ` `, not single quoted strings.
+ 1
Thank you ill check with console.log
+ 1
The backticks were the problem, i was using 'www.example.com/?a='+{queryString}. But it worked when i put `${queryString}` in backticks. Thank you!
0
Kate Atanasoska Where is the reference to the queryString in your code? What I mean is, where is the variable that holds that value declared in your code? Once you have that, you can use a template string to form your URL dynamically. So, if you have that in a variable called queryString, then you can do something like this.
`www.example.com/?a=${queryString}`
0
the query string is in the json file that i am mapping, but the problem is that when i use 'www.example.com/a='+{content.queryString}
The queryString cant be read it is giving 'any' and not returning the string from the json.
0
Here's the syntax for both ways.
1. Backticks:
onClick={()=>{
location.href = `www.example.com/?a=${queryString}`;
)
2. Regular string concatenation using single quotes:
onClick={()=>{
location.href = 'www.example.com/?a=' + queryString;
)
Update: you may have to do content.queryString if the queryString is definitely on each content object.
0
Awesome đ glad to hear that! Good luck with your app.