Reputation: 105
I'm struggling with conditional rendering views.
I usually use only double conditional rendering views, with a useState(true/false).
But today I need a triple conditional rendering view.
How can I build something like if color = red, you render red, if color = blue you render blue, if color = green you render green.
const TripleConditionalRendering = () => {
const [ color, setColor ] = useState("")
const handleClickRed = () => {
setColor("red")
}
const handleClickBlue = () => {
setColor("blue")
}
const handleClickRed = () => {
setColor("blue")
}
return (
<button onClick={handleClickRed}/>
<button onClick={handleClickBlue}/>
<button onClick={handleClickGreen}/>
{ color == red ? (
<p> the color is : red</p>
) : (
<p> the color is : blue or green, sorry cant make triple conditional rendering</p>
)}
// how can I add those ?
<p> the color is : blue</p>
<p> the color is : green</p>
)
}
Upvotes: 1
Views: 2033
Reputation: 11382
It looks like you've already worked out that if it's not red, it must be blue or green.
The format for a ternary is as follows: predicate ? true_expression : false_expression
Since you already know that if the statement is false, it can be one of the other options, just nest the ternary, like so:
predicate ? true_expression : (nested_predicate ? nested_true : nested false)
In your specific example, this becomes:
color == red
? <red/>
: color == blue
? <blue/>
: <green/>
Of course, logically, there's no reason why the logic for blue and green should be nested under the logic for red, or why any color should be nested under another. In this case it might make more sense and be more readable if there was one ternary per color:
{ color == red ? <red/> : null }
{ color == blue ? <blue/> : null }
{ color == green ? <green/> : null }
You could also use &&
{ color == red && <red/> }
{ color == blue && <blue/> }
{ color == green && <green/> }
Or perhaps a switch statement would be even more readable
Upvotes: 2