React Lesson 11: Conditional Rendering

⚛️ React CourseLesson 11 of 15 · 73% complete

React components show different things based on conditions. Conditional rendering patterns are everywhere in real apps — loading states, errors, authenticated vs guest views.

Ternary Operator — Use Everywhere

function UserGreeting({ isLoggedIn, userName }) {
  return (
    <div>
      {isLoggedIn
        ? <h1>Welcome back, {userName}!</h1>
        : <h1>Please log in to continue</h1>
      }
    </div>
  );
}

&& Short Circuit — Show or Hide

function Notification({ hasNew, count }) {
  return (
    <div>
      {hasNew && (
        <span className="badge">{count} new messages</span>
      )}
    </div>
  );
}

// Common patterns:
{isLoading && <Spinner />}
{error && <ErrorMessage message={error} />}
{data && <DataTable data={data} />}

Full Loading Pattern

function DataView({ url }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    fetch(url).then(r => r.json())
      .then(d => { setData(d); setLoading(false); })
      .catch(e => { setError(e.message); setLoading(false); });
  }, [url]);
  
  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!data) return null;
  return <div>{JSON.stringify(data)}</div>;
}

🏋️ Practice Task

Build an authentication flow. Create state: isLoggedIn, userName. If logged out: show a login form (just a username input and Login button). If logged in: show “Welcome, [name]!” and a Logout button. Toggle the state with the buttons.

💡 Hint: When Login is clicked: setIsLoggedIn(true) and setUserName(input value). When Logout: setIsLoggedIn(false).

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *