🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Expert Masterclasses.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEreact

react Documentation

LOADING ENGINE...

React Conditional Rendering with if/else

Master React components, hooks, and best practices.

Conditional Rendering with if/else

Author

Pascual Vila

Frontend Instructor.

Conditional rendering in React allows you to render different components or elements based on the component's state or props. A common approach is to use the if/else conditional structure to determine what to render.

Example with if/else:

      {`import React, { useState } from "react";

      function Conditional() {
        const [isLoggedIn, setIsLoggedIn] = useState(false);

        const handleLogin = () => setIsLoggedIn(true);
        const handleLogout = () => setIsLoggedIn(false);

        if (isLoggedIn) {
          return (
            <div>
              <h1>Welcome</h1>
              <button onClick={handleLogout}>Log Out</button>
            </div>
          );
        } else {
          return (
            <div>
              <h1>Please, log in</h1>
              <button onClick={handleLogin}>Log In</button>
            </div>
          );
        }
      }

      export default Conditional;`}