I
I
ironmansl2019-10-17 19:54:03
React
ironmansl, 2019-10-17 19:54:03

Why write code like this?

There is a code that changes classes (adds or removes):
https://jsfiddle.net/rjhzf0wk/
there is this line:

<div className={(this.state.opened) ? "mystyle" : ""}>Текст</div>

And I thought, why not write like this:
<div className="mystyle">{this.state.opened}Текст</div>

and in css write display:none for mystyle.
But that doesn't work.
I often see that in React code they write not the name of the class as the value of the className attribute, but some kind of condition is written in the className value. Why is it written that way? What kind of chip is this to write not the name of the class but the condition?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Telnov, 2019-10-17
@ironmansl

Because the first piece of code checks what value is stored in the state, and if true, sets the mystyle class. And your code creates a block with the mystyle class, and enters text into it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question