1

While using AND operator to evaluate the expression in line 6,

1. export default function App() {
2.  var isDone = false;
3.  const strikethrough = { textDecoration: "line-through" };
4.  return (
5.    <div className="App">
6.      <h1 style={isDone && strikethrough}>Hello CodeSandbox</h1>
7.    </div>
8.   );
9. }

when isDone = false, I am getting an error as

'The style prop expects a mapping from style properties to values, not a string. For example, style={‌{marginRight: spacing + 'em'}} when using JSX.

when isDone = true, things are working fine.

Somehow the null is not working and in order to check that, I used the following

<h1 style={}>Hello CodeSandbox</h1>

This gives an error that 'JSX attributes must only be assigned a non-empty expression'

I am learning ReactJs from an online course. What's happening here?

sankha
  • 213
  • 2
  • 7
  • 1
    Try `style={isDone ? strikethrough : {}}` – Yevhen Horbunkov Jul 03 '20 at 11:21
  • Yes, I tried

    Hello CodeSandbox

    , and this works fine but why doesn't the && operator work as intended in this case
    – sankha Jul 03 '20 at 11:49
  • It's because `&&` works like this. If whatever's before `&&` is truthy, it'll return whatever's after the `&&`. If whatever's before `&&` is falsy, it'll return the first value. which is usually `false`. That's what happens in your case. When the condition is false, it returns false and gets assigned to the style attribute – thealpha93 Jul 03 '20 at 11:56
  • @TheAlpha93 Thank you for this explanation. – sankha Jul 03 '20 at 12:01

2 Answers2

1

Try to console log your condition.

You should have this code:

<h1 style={isDone ? strikethrough : undefined}>

OR

<h1 style={isDone ? strikethrough : {}}>

const isDone = true
const strikethrough = 'yes' // or { textDecoration: "line-through" }

console.log(isDone && strikethrough) // return 'yes'

VS

const isDone = false
const strikethrough = 'yes'

console.log(isDone && strikethrough) // return boolean false

Problem is that boolean is not accepted by your style props.

More.

If you are using typescript you can inspect props of your h1 tag.

There is a className?: string; it is mean string or nothing.

So, you can't pass there boolean from isDone && strikethrough (return false).

JaLe
  • 409
  • 3
  • 13
  • Thank you so much, this explanation helped me a lot. I did console log the condition to understand – sankha Jul 03 '20 at 11:52
0

You cannot assign non-empty expression as you already figured out. So you'd need to do something like

<h1 style={isDone ? strikethrough : {}}>Hello CodeSandbox</h1>

in order to have a default style.

po.pe
  • 1,047
  • 1
  • 12
  • 27