DEV Community

Cover image for Conditional rendering in react || conditional rendering example in react
Anil
Anil

Posted on

Conditional rendering in react || conditional rendering example in react

Conditional rendering in React refers to the ability to render different content or components based on certain conditions. This allows you to dynamically show or hide parts of your UI based on user interactions, data fetched from an API, or any other condition.

Here's an example demonstrating conditional rendering:

import React, { useState } from 'react';

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

  // Function to handle login
  const handleLogin = () => {
    setIsLoggedIn(true);
  };

  // Function to handle logout
  const handleLogout = () => {
    setIsLoggedIn(false);
  };

  return (
    <div>
      {isLoggedIn ? (
        <div>
          <h1>Welcome, User!</h1>
          <button onClick={handleLogout}>Logout</button>
        </div>
      ) : (
        <div>
          <h1>Please log in</h1>
          <button onClick={handleLogin}>Login</button>
        </div>
      )}
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

In this example:

  • We have a state variable isLoggedIn initialized to false using the useState hook.
  • We have two functions: handleLogin and handleLogout, which respectively update the isLoggedIn state to true or false.
  • The isLoggedIn state variable is used to conditionally render different content.
  • If isLoggedIn is true, it renders a welcome message and a logout button. If isLoggedIn is false, it renders a login prompt and a login button.
  • Depending on the value of isLoggedIn, different JSX elements are rendered.

This is just a basic example, and conditional rendering can become more complex depending on the specific requirements of your application. You can use any JavaScript expressions within curly braces {} to determine the conditions for rendering.

Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js

Top comments (0)