I'm in the stage of learning JS and React and I'm not sure why else if doesn't work in the code below. Anyone can help me?
function Item({ name, isPacked }) {
if (isPacked) {
return (
<li className="item">
{name} {isPacked && " ✔"}
</li>
);
} else if (!isPacked) {
return (
<li className="item">
{name} {isPacked && " ❌"}
</li>
);
}
}
export default function PackingList() {
return (
<section>
<h1>Sally Ride's Packing List</h1>
<ul>
<Item isPacked={true} name="Space suit" />
<Item isPacked={true} name="Helmet with a golden leaf" />
<Item isPacked={false} name="Photo of Tam" />
</ul>
</section>
);
}
CodePudding user response:
Try like this:
function Item({ name, isPacked }) {
return (
<li className="item">
{`${name} ${isPacked ? "✔" : '❌'} `}
</li>
);
}
CodePudding user response:
you actually tested if the isPacked true or false so try this code:
function Item({ name, isPacked }) {
return (
<li className="item">
{name} {isPacked ? "✔" : "❌" }
</li>
);
}
{isPacked ? "✔" : "❌" } so this line of code is equal to:
if(isPacked == true){
return "✔";
}else{
return "❌";
}
You can get some helpful examples Here https://reactjs.org/docs/conditional-rendering.html.