— React, Conditional Rendering, JavaScript — 2 min read
Conditional rendering is a powerful technique in React that allows you to selectively render components based on certain conditions or states. It provides a way to control the appearance and behavior of your application's UI dynamically. In this article, we will explore different approaches to conditional rendering in React with practical examples.
One common way to conditionally render components in React is by using an if
statement or a ternary operator within JSX. For example, suppose we have a boolean variable isLoggedIn
that represents whether a user is logged in or not. We can use it to conditionally render a greeting message based on the login status:
1function Greeting({ isLoggedIn }) {2 if (isLoggedIn) {3 return <h1>Welcome back!</h1>;4 } else {5 return <h1>Please log in.</h1>;6 }7}
You can then use this Greeting
component in your application, passing the isLoggedIn
prop to conditionally render the appropriate message.
1function App() {2 const isLoggedIn = true;3
4 return (5 <div>6 <Greeting isLoggedIn={isLoggedIn} />7 </div>8 );9}
In this example, the h1
element rendered depends on the value of the isLoggedIn
prop.
Another approach for conditional rendering is to utilize the logical AND (&&
) operator. This technique is useful when you want to conditionally render a component or an element without providing an alternative. Consider the following example:
1function WarningBanner({ showWarning }) {2 return (3 <div>4 {showWarning && <p>Warning: This action is irreversible.</p>}5 </div>6 );7}
In this case, the <p>
element will only be rendered if the showWarning
prop is true
. Otherwise, nothing will be rendered.
React components often need to respond to changes in state and update their rendering accordingly. By using the useState
hook or class component's state, you can achieve dynamic rendering based on state values. Let's demonstrate this with a toggle button example:
1function ToggleButton() {2 const [isOn, setIsOn] = useState(false);3
4 const handleClick = () => {5 setIsOn(!isOn);6 };7
8 return (9 <button onClick={handleClick}>10 {isOn ? 'ON' : 'OFF'}11 </button>12 );13}
In this example, clicking the button toggles the state value of isOn
, causing the text inside the button to change between "ON" and "OFF". The component re-renders automatically when the state changes.
Sometimes, you may encounter situations where you need to handle multiple conditions for rendering different components. One way to achieve this is by using the switch
statement or a series of if-else
statements. Here's an example that demonstrates different greetings based on the time of day:
1function Greeting({ hour }) {2 let greeting;3
4 if (hour < 12) {5 greeting = 'Good morning';6 } else if (hour < 18) {7 greeting = 'Good afternoon';8 } else {9 greeting = 'Good evening';10 }11
12 return <h1>{greeting}!</h1>;13}
In this example, the Greeting
component renders a different greeting based on the value of the hour
prop. You can customize the conditions and responses according to your requirements.
In closing, conditional rendering is a vital concept in React that enables you to build dynamic and interactive user interfaces. By leveraging if statements, ternary operators, logical operators like &&
, and state management, you can control what components are rendered based on various conditions or states. Understanding these techniques empowers you to create more flexible and responsive React applications.