react

Introducing JSX : conditionals

MyaZ 2020. 6. 13. 13:41

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'));