Skip to content

Question 2

Design and develop a functional component named UserStatusSwitcher that toggles a user's status between “Online” and “Offline” using a button.

  • Use useState to manage status and onClick to update it.
  • Display the current status with conditional rendering.
  • Style the status text with inline CSS (e.g., green for online, red for offline).

UserStatusSwitcher.jsx

jsx
import React, { useState } from 'react';

function UserStatusSwitcher() {
  // State
  const [isOnline, setIsOnline] = useState(false);

  // Event Handler
  function toggleStatus() {
    setIsOnline(!isOnline);
  };

  // Dynamic Inline Styles
  const statusStyle = {
    color: isOnline ? 'green' : 'red',
    fontWeight: 'bold',
    fontSize: '1.2em',
    marginBottom: '10px'
  };
  const = divStyle = {
    textAlign: 'center', 
    marginTop: '40px'
  }

  return (
    <div style={divStyle}>
      <div style={statusStyle}>
        Status: {isOnline ? 'Online' : 'Offline'}
      </div>
      <button onClick={toggleStatus}>
        Toggle Status
      </button>
    </div>
  );
};

export default UserStatusSwitcher;

Made with ❤️ for students, by a fellow learner.