React allows you to conditionally render elements in your component based on some condition. This is useful when you want to display different content or behavior based on certain states or props.
Here are some examples of how to use conditional rendering in React:
import React from 'react';
function MyComponent(props) {
return (
{props.showContent && Some content to show
}
);
}
export default MyComponent;
In this example, we’re defining a functional component called MyComponent that conditionally renders a <p> element based on the value of the showContent prop. If the showContent prop is true, the content is rendered; otherwise, it is not.
import React, { useState } from 'react';
function MyComponent() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
function handleLogin() {
setIsLoggedIn(true);
}
return (
{isLoggedIn ? (
Welcome back!
) : (
)}
);
}
export default MyComponent;
In this example, we’re defining a functional component called MyComponent that conditionally renders a <p> element or a <button> element based on the value of the isLoggedIn state. If isLoggedIn is true, the <p> element is rendered to welcome the user back; otherwise, a <button> element is rendered to allow the user to log in.
import React from 'react';
function MyComponent(props) {
return (
{props.items.length > 0 ? (
{props.items.map(item => (
- {item.name}
))}
) : (
No items to display
)}
);
}
export default MyComponent;
In this example, we’re defining a functional component called MyComponent that conditionally renders a list of items or a message if there are no items to display. The condition is based on the length of the items prop array. If the length is greater than zero, a <ul> element is rendered with each item as an <li> element; otherwise, a <p> element is rendered to display a message that there are no items to display.
Overall, conditional rendering is a powerful feature of React that allows you to create dynamic and responsive user interfaces. By conditionally rendering elements based on certain states or props, you can create complex user interfaces that are easy to maintain and update.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.