logo

Conditional Rendering in React

A React component that demonstrates conditional rendering.

9 Stars

Code

import React, { useState } from 'react';

const ConditionalRendering = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome back!</h1>
      ) : (
        <h1>Please log in.</h1>
      )}
      <button onClick={() => setIsLoggedIn(!isLoggedIn)} className="mt-4 bg-blue-500 text-white py-2 px-4 rounded">
        {isLoggedIn ? 'Log out' : 'Log in'}
      </button>
    </div>
  );
};

export default ConditionalRendering;

Explanation

This component demonstrates conditional rendering using a state variable isLoggedIn. Depending on the value of isLoggedIn, the component renders either a welcome message or a prompt to log in. A button toggles the state between logged in and logged out.