Conditional Rendering in React
In React, conditional rendering is a technique used to render components conditionally based on certain conditions. It allows you to control what gets displayed in the UI based on the state or props of the component.
Conditional rendering is useful when you want to show different content or components based on certain situations. For example, you may want to display a loading spinner while data is being fetched, or show different components based on user authentication status.
To perform conditional rendering in React, you can use various techniques, including:
Inline If with Logical && Operator: You can use the logical && operator to conditionally render an element. If the condition is true, the element will be rendered; otherwise, it won't be included in the output.
JAVASCRIPT1const isLoggedIn = true; 2 3function Greeting() { 4 return ( 5 <div> 6 <h1>Welcome back!</h1> 7 </div> 8 ); 9} 10 11function App() { 12 return ( 13 <div> 14 {isLoggedIn && <Greeting />} 15 </div> 16 ); 17} 18 19ReactDOM.render( 20 <App />, 21 document.getElementById('root') 22);
Element Variables: You can use variables to store elements and render them based on conditions. By modifying the value of the variable, you can control the rendered output.
JAVASCRIPT1const isLoggedIn = true; 2 3function Greeting() { 4 return ( 5 <div> 6 <h1>Welcome back!</h1> 7 </div> 8 ); 9} 10 11function App() { 12 let element; 13 14 if (isLoggedIn) { 15 element = <Greeting />; 16 } else { 17 element = <Login />; 18 } 19 20 return ( 21 <div> 22 {element} 23 </div> 24 ); 25} 26 27ReactDOM.render( 28 <App />, 29 document.getElementById('root') 30);
Conditional Rendering with Ternary Operator: You can use the ternary operator to conditionally render elements based on a condition. If the condition is true, the first expression will be returned; otherwise, the second expression will be returned.
JAVASCRIPT1const isLoggedIn = true; 2 3function Greeting() { 4 return ( 5 <div> 6 <h1>Welcome back!</h1> 7 </div> 8 ); 9} 10 11function App() { 12 return ( 13 <div> 14 {isLoggedIn ? <Greeting /> : <Login />} 15 </div> 16 ); 17} 18 19ReactDOM.render( 20 <App />, 21 document.getElementById('root') 22);
By leveraging conditional rendering in React, you can create dynamic and responsive UIs that adapt to different scenarios and user interactions.
xxxxxxxxxx
// replace with JavaScript logic relevant to content
// make sure to log something
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log('FizzBuzz');
} else if (i % 3 === 0) {
console.log('Fizz');
} else if (i % 5 === 0) {
console.log('Buzz');
} else {
console.log(i);
}
}