EN
React - conditional rendering
0 points
In this article, we would like to show you conditional rendering in React.
Below example presents how to render a shopping list if there are any items to buy, otherwise render a header with information.
Practical example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const ShoppingListItem = (props) => {
6
return (
7
<p>{props.id} {props.name}</p>
8
);
9
}
10
11
const App = () => {
12
const [list, setList] = React.useState([{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }]);
13
14
const itemCounter = list.length;
15
return (
16
<div>
17
{itemCounter === 0
18
? <h1>no items to buy</h1>
19
: list.map(item =>
20
<ShoppingListItem
21
key={item.id}
22
id={item.id}
23
name={item.name}
24
/>
25
)
26
}
27
</div>
28
);
29
}
30
31
const root = document.querySelector('#root');
32
ReactDOM.render(<App />, root);