AND operator in ReactJs

1k Views Asked by At

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?

2

There are 2 best solutions below

1
JaLe On BEST ANSWER

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).

0
po.pe On

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.