Logical AND (&&)
- React course
- Beginner
- Lesson 24/84
- 4 min
Learn the condition && element pattern and its pitfalls.
Logical AND (&&)
The logical AND pattern looks like { 'condition && element' }. If the condition is true, element renders; otherwise nothing happens. It's ideal for one-sided show when situations.
Example: { 'hasError && <Error />' }. If hasError is true, Error renders; otherwise nothing.
Beware: if the condition returns a falsy value like 0, React may print 0 on screen. So make sure the condition is boolean: { 'hasError === true && <Error />' } is safer.
&& pitfall
When you write { 'count && <List />' }, if count is 0 React may print 0 on screen. This is because 0 is rendered as a numeric value.
Two common fixes: turn the condition into a boolean (count > 0) or use !!count to make it an explicit boolean.
Ternary also works: { 'count > 0 ? <List /> : null' }. This removes the 0 problem entirely.
Practice Show error message
Complete the skeleton. Write a component called ErrorBox that takes ({ '{ hasError }' }) as parameter. If hasError === true, return <p className="error">An error occurred</p>; otherwise null (with &&). Don't forget to export.
Starter code
// Write the ErrorBox component hereSample solution
function ErrorBox({ hasError }) {
return hasError === true && <p className="error">An error occurred</p>;
}
export default ErrorBox;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is the && pattern used?
- To store state
- To choose between two options
- To show only when a condition holds Correct answer
- To update DOM
Explanation: && is ideal for one-sided conditional render.
2 && operator
The && pattern: ____ condition && element.
The && pattern: condition condition && element.
Explanation: condition && element is the pattern.
3 Match the && pattern
| Term | Meaning |
|---|---|
condition |
Question |
&& |
Operator |
element |
Result |
0 |
Risk |