You can add conditinal statement in JSX like this.
function getNum() {
return Math.floor(Math.random() * 10) + 1;
}
// option 1-a,b
class NumPicker extends React.Component {
render() {
const num = getNum();
return (
<div>
<h1>Your number is...{num}</h1>
<p>
{num === 7 ? 'Lucky!' : 'Try again'}</p>
{
num === 7
? <img src="https://thumbnail.10x10.co.kr/webimage/image/basic600/176/B001768023-4.jpg?cmd=thumb&w=500&h=500&fit=true&ws=false" />
: null
// 이거도 가능
// num === 7 && <img src="https://thumbnail.10x10.co.kr/webimage/image/basic600/176/B001768023-4.jpg?cmd=thumb&w=500&h=500&fit=true&ws=false" />
}
</div>
);
}
}
// option 2
class NumPicker extends React.Component {
render() {
const num = getNum();
let msg;
if (num === 7) {
msg =
<div>
<p>Lucky!</p>
<img src="https://thumbnail.10x10.co.kr/webimage/image/basic600/176/B001768023-4.jpg?cmd=thumb&w=500&h=500&fit=true&ws=false" />
</div>
} else {
msg = <p>Try again!</p>
}
return (
<div>
<h1>Your number is...{num}</h1>
{msg}
</div>
);
}
}
ReactDOM.render(<NumPicker />, document.getElementById('root'));
'react' 카테고리의 다른 글
Props : types of props (0) | 2020.06.13 |
---|---|
Introducing Props! and more.. (0) | 2020.06.13 |
Introducing JSX : basic concept of React layout (0) | 2020.06.13 |
Introducing JSX : basic (0) | 2020.06.13 |
class component vs function component (0) | 2020.06.13 |