0

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>
  );
}
8
  • 5
    What isn't working? Also, using {isPacked && " ❌"} when you just checked !isPacked means it will never be displayed. Commented Aug 23, 2022 at 15:27
  • Please provide some more info. What exactly isn't working? Are there any errors? etc.. Commented Aug 23, 2022 at 15:27
  • 1
    You don't need an if/else there. You can use a ternary statement in one line: {name} {isPacked ? '✔' : '❌'} Commented Aug 23, 2022 at 15:32
  • @Spectric yes I can use logical AND and maybe ternary operator but I wanted to test with IF-Else if. Im not getting any error message I'm just expecting in the third component <Item> to get X next to the text. Commented Aug 23, 2022 at 15:33
  • 1
    You won't get an error because the code works - it just doesn't work the way you want it to. Remove the isPacked checks from within the if/else as Spectric pointed out - you've already made them. PS - I said you don't need it, not that you can't use it. Commented Aug 23, 2022 at 15:35

2 Answers 2

2

Try like this:

function Item({ name, isPacked }) {
    return (
        <li className="item">
            {name} {isPacked ? '✔' : '❌'}
        </li>
    );
}
Sign up to request clarification or add additional context in comments.

4 Comments

There's no need for the template string here.
What is the alternative could you share please
See my previous comment, or the other answer.
I just checked it, thank you for information.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.