September 27, 2022

React Conditional Rendering With Examples

In this tutorial we'll see different ways of conditional rendering in React. Conditional rendering is the ability to show different sections of code based on whether the condition is true or false. In terms of React where UI is rendered, it means rendering different elements or components based on a condition.

Conditional rendering in React

Conditional rendering in React uses the same conditional statements or operators used in JavaScript. You can use if-else, switch-case, conditional operator (ternary operator) in React.

Conditional rendering in React can be done in following ways-

  • If-else
  • Conditional or ternary operator
  • Logical operator (&&)
  • Switch case

Using if

If-else is a de facto conditional statement used in almost all the programming languages. If the condition is true if block is executed otherwise else block is executed. Note that else is optional.

Conditional rendering with if in React example

Let's take an example where we have two components LoginButton and LogoutButton and one of them is to be rendered.

  • If already logged in then show the logout button
  • If not logged in then show the login button.

LoginButton.js

const LoginButton = (props) => {
    return (
        <div>
            <h3>Login to see the site content</h3>
            <button onClick={props.onClick}>Login</button>
        </div>
    )
}

export default LoginButton;

LogoutButton.js

const LogoutButton = (props) => {
    return (
        <div>
            <h3>Welcome to our site</h3>
            <button onClick={props.onClick}>Logout</button>
        </div>
    )
}
export default LogoutButton;

Logic to conditionally render one of these component is in App.js where useState() hook is used to track the login state. If isLoggedIn is false then LoginButton component is rendered, LogoutButton component is rendered otherwise.

Uses the button variable to store element.

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const loginActionHandler = () => {
    setIsLoggedIn(true);
  }
  const logoutActionHandler = () => {
    setIsLoggedIn(false);
  }
  let button;
  if(isLoggedIn){
    button = <LogoutButton onClick={logoutActionHandler}></LogoutButton>
  }else{
    button = <LoginButton onClick={loginActionHandler}></LoginButton>
  }
  return (
   <div>
    {button}
   </div>
  );
};
export default App;
Conditional rendering in React
Conditional rendering in React using if

Using Conditional or ternary operator

You can also use ternary operator (?:) which takes three operands for conditional rendering in React. Ternary operator can be used as an substitute of if-else to make your code more compact.

If we take the same example as used above then it needs a small change in App.js

  return (
   <div>
    {isLoggedIn ? <LogoutButton onClick={logoutActionHandler} /> :  <LoginButton onClick={loginActionHandler} />}
   </div>
  );

Using Logical operator (&&) to conditionally render

The JavaScript logical && operator can also be used for conditionally including an element. in fact it is used very frequently in React for conditonal rendering.

In condition && expression, if condition is true then the statement evaluates to expression. In case condition is false then the statement evaluates to false.

Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

If we take the same example as used above then it needs a small change in App.js to start using logical operator.

  return (
    <div>
      {!isLoggedIn && <LoginButton onClick={loginActionHandler}></LoginButton>}
      {isLoggedIn && <LogoutButton onClick={logoutActionHandler}></LogoutButton>}
    </div>
  );

Using a switch statement

You can also use a switch statement where you can specify different elements in different case statements. If you have multiple conditions switch is considered a more readable option than if- else if statements.

In our example where we are trying to conditionally render login or logout button change in App.js for using switch is as given below.

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const loginActionHandler = () => {
    setIsLoggedIn(true);
  }
  const logoutActionHandler = () => {
    setIsLoggedIn(false);
  }
  let button;
  switch(isLoggedIn){
    case true:
      button = <LogoutButton onClick={logoutActionHandler}></LogoutButton>
      break;
    case false: 
      button = <LoginButton onClick={loginActionHandler}></LoginButton>
      break;
    default:  
      button = null;
  }
  return (
   <div>
    {button}
   </div>
  );
};

export default App;

That's all for the topic React Conditional Rendering With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment