> For the complete documentation index, see [llms.txt](https://max-frontend.gitbook.io/react-course-ru/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://max-frontend.gitbook.io/react-course-ru/if-else_v_jsx.md).

# If-else, тернарный оператор

*ОБНОВЛЕНИЕ 2018: в учебнике хорошая теория, но ему уже два года. Проверяйте версии пакетов. За выходом нового учебника можно следить в* [*telegram канале*](http://bit.ly/2tS7QUC) *или* [*twitter*](http://bit.ly/2HADDLE)

*На* [*канале*](http://bit.ly/2tS7QUC) *так же проводятся бесплатные вебинары, публикуются переводы и авторские материалы,* [*присоединяйтесь*](http://bit.ly/2tS7QUC)*!*

## If-else, тернарный оператор

Помните, у нас была фраза "новостей нет"? Хорошо бы ее отображать, если новостей действительно нет.

Для начала, научимся отображать общее количество новостей, допустим внизу, после списка новостей.

Как бы сказал участник игры "Угадай JS" - я напишу это за одну строку. Что скажете вы? Подсказка:

```javascript
var News = React.createClass({
  render: function() {
    var data = this.props.data;
    var newsTemplate = data.map(function(item, index) {
      return (
        <div key={index}>
          <p className="news__author">{item.author}:</p>
          <p className="news__text">{item.text}</p>
        </div>
      )
    })

    return (
      <div className="news">
        {newsTemplate}
        ЭТА_СТРОКА_ЗДЕСЬ
      </div>
    );
  }
});
```

**Ответ:**

```javascript
<strong>Всего новостей: {data.length}</strong>
```

Поиграйтесь с переменной *my\_news*. Сделайте ее пустым массивом, добавьте/удалите элементы. Пообновляйте страницу. Количество новостей должно работать корректно.

Вернемся к нашей задаче. Алгоритм прост:

Создаем переменную *newsTemplate*, если новости есть - в переменную по-прежнему будем передавать результат работы фунции map, иначе - будем передавать сразу разметку.

Компонент News:

```javascript
var News = React.createClass({
  render: function() {
    var data = this.props.data;
    var newsTemplate;

    if (data.length > 0) {
      newsTemplate = data.map(function(item, index) {
        return (
          <div key={index}>
            <p className="news__author">{item.author}:</p>
            <p className="news__text">{item.text}</p>
          </div>
        )
      })
    } else {
      newsTemplate = <p>К сожалению новостей нет</p>
    }

    return (
      <div className="news">
        {newsTemplate}
        <strong>Всего новостей: {data.length}</strong>
      </div>
    );
  }
});
```

Неплохо, но если нет новостей - зачем нам показывать, что всего новостей 0? Давайте решим это с помощью css класса *.none*, который будем добавлять если новостей нет.

Для этого создайте css файл с содержимым:

*css/app.css*

```css
.none {
  display: none !important;
}
```

и подключите его в index.html

*index.html*

```markup
<!DOCTYPE html>
<html>
  <head>
    <title>React [RU] Tutorial</title>
    <link rel="stylesheet" href="css/app.css">
  </head>
  <body>
    <div id="root"></div>

    <script src="js/react/react.js"></script>
    <script src="js/react/react-dom.js"></script>
    <script src="js/react/browser.min.js"></script>
    <script type="text/babel" src="js/app.js"></script>
  </body>
</html>
```

С классом *.none* все вновь решается в одну строку.

Измените строку про количество новостей следующим образом:

```javascript
<strong className={data.length > 0 ? '':'none'}>Всего новостей: {data.length}</strong>
```

Проще простого: *есть новости ? ' пустой класс ' : ' класс .none '*

Для работы с классами, когда их становится больше и условия становятся сложнее, можно использовать [classNames (NPM пакет)](https://www.npmjs.com/package/classnames). Но сейчас в этом нет необходимости.

**Итого**: если вам нужно отобразить что-то в зависимости от условий, делайте это так же, как если бы react не был подключен. Для удобства, мы использовали *переменную-шаблон*, которую объявили **заранее**, а затем в зависимости от условия сохраняли в нее необходимую разметку.

[Исходный код](https://github.com/maxfarseer/react-ru-tutorial/tree/if-else-jsx) на данный момент.

P.S. [официальная документация про If-else внутри JSX](https://facebook.github.io/react/tips/if-else-in-JSX.html)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://max-frontend.gitbook.io/react-course-ru/if-else_v_jsx.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
