Reputation: 1544
const ModalButton = ({ label, mode }) => {
return (
<button type="submit">
{mode == "new" && (
<FaPlusCircle style={{ fontSize: "20px", paddingTop: "6px" }} />) label
}
</button>
);
};
This label is underlined as red in my code editor. Why it won't let me to have JavaScript with JSX?
Upvotes: 1
Views: 68
Reputation: 24915
As rightly commented by @Konrad Linkowski
This is invalid syntax
What is the issue with it?
What you are using is called expression. So condition1 && condition2 will return false
if condition1 is falsey or will return condition2.
In your expression, its condition1 && condition2 condition3
. There needs to be an operator between condition2 and condition3 or they need correct structure.
If you want label
to always render and icon for "new"
buttons, it should be:
{condition1 && condition2}
{condition3}
but if you need them to render together or none, you need to wrap then so that your expression returns 1 value:
{
condition1 &&
(<>
element1
element2
</>)
}
Sample
const ModalButton1 = ({ label, mode }) => {
return (
<button type="submit">
{
mode == "new" && (
<FaPlusCircle style={{ fontSize: "20px", paddingTop: "6px" }} />)
}
{ label }
</button>
);
};
const ModalButton2 = ({ label, mode }) => {
return (
<button type="submit">
{
mode == "new" && (
<>
<FaPlusCircle style={{ fontSize: "20px", paddingTop: "6px" }} />)
{label}
</>
}
</button>
);
};
Upvotes: 2
Reputation: 34
A JSX expression can only return a single value. If you want to return several values, wrap them in an array, like so:
{mode == "new" && [<Component/>, label]}
Upvotes: 0
Reputation: 1074285
The second operand of &&
has to be a single value; right now, you're trying to give it two. To treat the icon and the text node after it as a unit (a single value), you need to wrap them in something, such as a fragment: <>_____</>
const ModalButton = ({ label, mode }) => {
return (
<button type="submit">
{mode == "new" && (
<>
<FaPlusCircle style={{ fontSize: "20px", paddingTop: "6px" }} />
{label}
</>
)}
</button>
);
};
(You also had the )
in the wrong place; I've fixed it above. It shouldn't be just after the icon, it should be after the entire operand for &&
[so with this change, it's after the end of the fragment].)
Also, if you want to use the value of label
, you'll need to wrap it in a JSX expression (as above): {label}
.
Upvotes: 3