Conditional rendering in React means rendering different UI elements depending on specific conditions. These conditions are usually based on state, props, or computed values. React does not have a special syntax for conditional rendering; instead, it uses standard JavaScript expressions inside JSX to decide what should be displayed.
The most basic form of conditional rendering uses an if statement outside JSX. This approach is useful when the logic is complex or when entire components need to be conditionally returned.
Example using if statement:
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please log in</h1>;
}
This method keeps JSX clean and is easy to understand for larger conditions.
Another common way to implement conditional rendering is using the ternary operator. This is useful when you want to switch between two UI elements inline within JSX.
Example using ternary operator:
function Status({ isOnline }) {
return <p>{isOnline ? "Online" : "Offline"}</p>;
}
The ternary operator is concise and widely used for simple conditions.
For cases where you want to render something only when a condition is true and nothing otherwise, the logical AND (&&) operator is commonly used.
Example using logical AND:
function Notification({ hasMessage }) {
return hasMessage && <p>You have a new message</p>;
}
If hasMessage is false, React renders nothing. This is useful for optional UI elements like alerts or badges.
Conditional rendering is also frequently used with lists and dynamic content. For example, showing a loading message while data is being fetched and displaying content once the data is available.
Example with loading state:
function DataView({ isLoading, data }) {
if (isLoading) {
return <p>Loading...</p>;
}
return <p>{data}</p>;
}
A real-world example of conditional rendering can be seen in authentication-based applications. When a user is logged in, the application shows a dashboard; when the user is logged out, it shows a login form. Conditional rendering ensures that users see only the UI relevant to their current state.
Another practical scenario is form validation. Error messages are displayed only when validation fails, and success messages appear only after successful submission. This keeps the UI clean and responsive.
Important best practices include keeping conditional logic simple, avoiding deeply nested conditions inside JSX, and moving complex logic outside JSX when needed. Clear conditions improve readability and reduce bugs.
In summary, conditional rendering allows React applications to dynamically display content based on state, props, or logic. It is a fundamental concept for building interactive and user-friendly React interfaces that respond intelligently to changing conditions.