Conditional Rendering
In conditional rendering in React, we display different parts of the UI based on specific conditions. This is useful for creating dynamic and responsive interfaces.
For example, imagine an application that displays welcome messages for logged-in users and a login button for unauthenticated users. We can use a conditional structure to decide which component to show.
import React from 'react';
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <button>Login</button>;
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {isLoggedIn: false};
}
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
</div>
);
}
}
export default App;
In this example, the ‘Greeting
‘ component decides whether to display a welcome message or a login button based on the state of ‘isLoggedIn
‘.
We use an ‘if
‘ structure to check the condition and return the appropriate component. This keeps our code clean and easy to understand.
By mastering conditional rendering in React, you can create smarter and more adaptable interfaces for your users.