Piotr Żak
Piotr Żak

Reputation: 2132

How to add icon inside React if condition

so i have rendering Todo {text}

How can I add condition inside 'li' like this:

if (completed){ render this}

else{ render this} ?

const Todo = ({ onClick, completed, text }) => (
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? 'line-through' : 'none'
    }}
  >
    {text}
  </li>
)

Upvotes: 2

Views: 4141

Answers (1)

Tholle
Tholle

Reputation: 112777

You can use the ternary operator just like you do for your textDecoration.

Example

const Todo = ({ onClick, completed, text }) => (
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? "line-through" : "none"
    }}
  >
    {text}
    {completed ? (
      <img src="https://picsum.photos/g/200/200/?random" />
    ) : (
      <img src="https://picsum.photos/200/200/?random" />
    )}
  </li>
);

ReactDOM.render(
  <Todo onClick={() => {}} completed text="Foo" />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 1

Related Questions