+ 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.

2nd Apr 2021, 1:34 PM
Kate Atanasoska
Kate Atanasoska - avatar
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.
2nd Apr 2021, 2:04 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 1
Thank you ill check with console.log
2nd Apr 2021, 2:11 PM
Kate Atanasoska
Kate Atanasoska - avatar
+ 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!
2nd Apr 2021, 2:18 PM
Kate Atanasoska
Kate Atanasoska - avatar
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}`
2nd Apr 2021, 1:49 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
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.
2nd Apr 2021, 1:55 PM
Kate Atanasoska
Kate Atanasoska - avatar
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.
2nd Apr 2021, 2:12 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
0
Awesome 🎉 glad to hear that! Good luck with your app.
2nd Apr 2021, 2:25 PM
CamelBeatsSnake
CamelBeatsSnake - avatar