ReasonJun

React : Conditional render 본문

Frontend/React

React : Conditional render

ReasonJun 2023. 6. 11. 15:46
728x90

Conditional rendering in React refers to the ability to display different components or content based on certain conditions or logical expressions. It allows you to control what gets rendered to the DOM based on the state or props of your components.

 

There are several ways to implement conditional rendering in React:

  • if statement: You can use a standard JavaScript if statement to conditionally render components. For example:
function MyComponent(props) {
  if (props.isLoggedIn) {
    return <LoggedInComponent />;
  } else {
    return <LoggedOutComponent />;
  }
}
  • Ternary operator: The ternary operator (condition ? expression1 : expression2) is a concise way to conditionally render components. For example:
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn ? <LoggedInComponent /> : <LoggedOutComponent />}
    </div>
  );
}
  • Logical && operator: The && operator can be used to conditionally render a component based on a condition. It is useful when you want to render a component only if a certain condition is true. For example:
function MyComponent(props) {
  return (
    <div>
      {props.isLoaded && <DataComponent />}
    </div>
  );
}
  • Switch statement: If you have multiple conditions to check, you can use a switch statement for more complex conditional rendering. For example:
function MyComponent(props) {
  switch (props.status) {
    case 'loading':
      return <LoadingComponent />;
    case 'success':
      return <SuccessComponent />;
    case 'error':
      return <ErrorComponent />;
    default:
      return <DefaultComponent />;
  }
}
728x90
Comments