8. Conditional Rendering and Lists
Level: BeginnerDuration: 20m
What is Conditional Rendering?
Conditional rendering means we decide what to show in the UI based on some condition. Think of it like saying: if this is true, show this element, otherwise show something else.
Using if Statements
jsx
function WelcomeMessage({ isLoggedIn }) {
if (isLoggedIn) {
return <h2>Welcome back!</h2>
}
return <h2>Please log in</h2>
}Using Ternary Operator
The ternary operator is a shorter way to write conditional rendering and is very common in React.
jsx
function WelcomeMessage({ isLoggedIn }) {
return <h2>{isLoggedIn ? 'Welcome back!' : 'Please log in'}</h2>
}Logical AND (&&) Rendering
Sometimes you only want to show something if a condition is true. In that case, you can use `&&`.
jsx
function Notification({ hasMessages }) {
return (
<div>
{hasMessages && <p>You have new messages!</p>}
</div>
)
}Rendering Lists with map()
To display a list in React, we use JavaScript's `map()` method to loop through an array and return JSX for each item.
jsx
const users = ['Ada', 'Grace', 'Linus']
function UserList() {
return (
<ul>
{users.map((user, index) => (
<li key={index}>{user}</li>
))}
</ul>
)
}React needs a unique `key` for each list item to track changes and avoid warnings.
Mini Project Step
In your `App.jsx`, add a list of features for your project and display them using `map()`. Also add a toggle button to show or hide the list.
jsx
// App.jsx
import { useState } from 'react'
function App() {
const features = ['Reusable components', 'Fast rendering', 'Simple UI updates']
const [showList, setShowList] = useState(true)
return (
<div>
<button onClick={() => setShowList(!showList)}>
{showList ? 'Hide Features' : 'Show Features'}
</button>
{showList && (
<ul>
{features.map((feature, index) => (
<li key={index}>{feature}</li>
))}
</ul>
)}
</div>
)
}
export default App