Welcome back to CodeYourCraft! Today, we're diving into a powerful feature of React JS - Conditional Rendering. This technique allows us to display different UI elements based on certain conditions, making our applications more dynamic and interactive. š” Pro Tip: Conditional rendering is a must-know skill for any React developer.
In simple terms, conditional rendering is a way to show or hide UI components based on a given condition. This is achieved by using JavaScript expressions within JSX. Let's see how it works with an example.
Let's create a simple component that displays either a "Yes" or "No" message based on a boolean value.
import React from 'react';
function ConditionalMessage(props) {
if (props.isApproved) {
return <p>Yes</p>;
} else {
return <p>No</p>;
}
}
export default ConditionalMessage;š Note: In the example above, we're using the if statement to check if the isApproved prop is true or false. Depending on the result, we return either "Yes" or "No".
Another way to achieve conditional rendering is by using the Ternary Operator. It allows us to write concise code by combining an if-else statement in a single line.
import React from 'react';
function ConditionalMessage(props) {
return (
<p>{props.isApproved ? 'Yes' : 'No'}</p>
);
}
export default ConditionalMessage;š Note: In the ternary operator, we use the syntax condition ? expressionIfTrue : expressionIfFalse. In this case, if isApproved is true, we display "Yes"; otherwise, we display "No".
Conditional rendering is not limited to simple text or boolean values. We can also use it to render different components based on certain conditions.
import React from 'react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
function ConditionalComponents(props) {
if (props.isConditionMet) {
return <ComponentA />;
} else {
return <ComponentB />;
}
}
export default ConditionalComponents;Now, let's create a practical example that displays different UI components based on user input.
import React, { useState } from 'react';
function UserInput(props) {
const [age, setAge] = useState('');
function handleChange(event) {
setAge(event.target.value);
}
return (
<div>
<label>Enter your age:</label>
<input type="number" value={age} onChange={handleChange} />
{age >= 18 && <p>You are eligible to vote.</p>}
{age < 18 && <p>You are not eligible to vote.</p>}
</div>
);
}
export default UserInput;š Note: In this example, we're using the useState hook to manage the user's input. Depending on the user's age, we display either "You are eligible to vote." or "You are not eligible to vote."
What is Conditional Rendering in React JS?
With this, we've covered the basics of JSX Conditional Rendering. Now that you know how to make your React components dynamic and responsive, you can create more engaging and interactive user interfaces. Keep practicing, and happy coding! š” Pro Tip: Try to implement conditional rendering in your next project and see the difference it makes.