I am trying to use a passed prop in a ternary operator, but I can’t seem to get it working. I have included a sample of the code, not the actual code, but I feel this captures the issue without necessarily including a long line of code. I want to add a condition: if props passed =“Good” then let the statement change to “that’s a nice word”
function Speak(props){
return(
<div>
// I want to add a condition
It is not nice to say <strong>{props.word}</strong>!
</div>
);reformatted text
function Speak(props){
return(
<div>
{props.word}==="Good" ? "that's a nice word" :
"Its not nice to say"{props.word}
</div>
);
Your syntax is wrong for the false side of ternary operator.
You’ll need to concat {props.word} to your string or use template literals.
Firstly, If you want to use JavaScript in JSX, all of it must be wrapped in curly braces between the opening and closing tags of the elements, then you just write the javaScript as you normally would, for example
<h1>{// All JavaScript goes here }</h1>
<div>{// All JavaScript goes here }</div>
Secondly, as far as the ternary operator goes, I suggest you review this first:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator/
where, if your condition to be met is that x is equal to y, then the following expression would yield ‘x is equal to y’ if it is true, and ‘x is not equal to y’ if not true
x === y ? 'x is equal to y' : 'x is not equal to y'
Try to make it work with the above 2 pieces of info, hint: x =props.word
in your case and y is…
Thanks a lot for the tip. I just figured it out some minutes ago.... here is what i did ```
function Speak(props) {
return (
<div>
{props.word === "Good"
? <span>
That's a nice word!</span>
: <span>It is not nice to say
<strong>{props.word}</strong>!</span>
}
</div>
)
}