react tidak mempunyai shortcut seperti mana framework yang lain ia menggunakan skill javascript yang ori cuma dengan gaya react
1. if else
if (coinToss() === 'heads') { img = ( <img src={pics.kitty} /> ); } else { img = ( <img src={pics.doggy} /> ); }
if coinToss = heads
img = img pics.kitty,
else
img = img pics.doggy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import React from 'react'; import ReactDOM from 'react-dom'; function coinToss() { // This function will randomly return either 'heads' or 'tails'. return Math.random() < 0.5 ? 'heads' : 'tails'; } const pics = { kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg', doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg' }; let img; // if/else statement begins here: if (coinToss() === 'heads') { img = ( <img src={pics.kitty} /> ); } else { img = ( <img src={pics.doggy} /> ); } ReactDOM.render(img, document.getElementById('app')); |
2. Or using ternary Operator
1 | const img = <img src={ pics[coinToss() === 'heads' ? 'kitty' : 'doggy'] } />; |
scenario : if coinToss = head it should display kitty else its doggy
HOW TO WRITE OR ITS STRUCTURE?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import React from 'react'; import ReactDOM from 'react-dom'; function coinToss () { // Randomly return either 'heads' or 'tails'. return Math.random() < 0.5 ? 'heads' : 'tails'; } const pics = { kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg', doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg' }; const img = <img src={ pics[coinToss() === 'heads' ? 'kitty' : 'doggy'] } />; ReactDOM.render( img, document.getElementById('app') ); |
2. USING && CONDITION
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import React from 'react'; import ReactDOM from 'react-dom'; // judgmental will be true half the time. const judgmental = Math.random() < 0.5; const favoriteFoods = ( <div> <h1>My Favorite Foods</h1> <ul> <li>Sushi Burrito</li> <li>Rhubarb Pie</li> { !judgmental &&<li> Nacho Cheez Straight Out The Jar</li>} <li>Broiled Grapefruit</li> </ul> </div> ); ReactDOM.render( favoriteFoods, document.getElementById('app') ); |