'If statement in Jsx render based on data
Whats simplest way to write a if statement in jsx when its based on data your receiving
how can i check the other code at the same time-if that makes sense? so if its not "P" then i want to make sure the other value is deffo a "L"?
code = P so output “Walking” code = L so output "Running"
text={
if(exercise.code = P)
{ "Walking"}
else (exercise.code = L)
{"Running"}}
Solution 1:[1]
{
exercise?.code === "P" ? "Walking" : exercise?.code === "L" ? "Running"
: null
}
Here {} means you are in JS and can write if conditions. ? : is ternary operator.
Solution 2:[2]
{ exercise.code === "P" ? "Walking" : "Running" }
Solution 3:[3]
Create an object to use as a mapping:
const codeMap = {
C: "Crawling",
P: "Walking",
L: "Running"
};
Then you can perform a lookup in your JSX:
... { codeMap[excercise?.code] || "Unknown/missing code" } ...
That will allow you to have as many codes as you want, and the JSX will not have to be changed.
Solution 4:[4]
switch(excercise?.code){
case 'P': return 'Walking';
case 'L': return 'Running';
}
Solution 5:[5]
this will solve your problem
{exercise.code == "P" && "Walking" || exercise.code == "L" && "Runing"}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asad Ashraf |
| Solution 2 | Dreamy Player |
| Solution 3 | Pier Paolo Ramon |
| Solution 4 | Nicholas Barfknecht |
| Solution 5 | mmh4all |
