[React] 4강 조건부 렌더링

1. if 문 사용

가장 기본적인 방법으로 if문이 있습니다. if문은 조건에 따라 렌더링할 내용을 결정합니다.

import React from 'react';

class MyComponent extends React.Component {
  render() {
    const isLoggedIn = true; // 또는 false로 설정

    if (isLoggedIn) {
      return <h1>환영합니다!</h1>;
    } else {
      return <h1>로그인 해주세요.</h1>;
    }
  }
}

export default MyComponent;

2. 삼항 연산자

삼항 연산자를 사용하면 코드를 더욱 간결하게 작성할 수 있습니다.

import React from 'react';

const Trinomial = () => {
  const isLoggedIn = true; // or false
  return <h1>{isLoggedIn ? 'Hello' : 'Please Login!!'}</h1>;
};

export default Trinomial;

3.논리 연산자

&& 연산자를 사용해 조건이 참일 때만 특정 내용을 렌더링 할 수 있습니다.

import React from 'react';

const Operator = () => {
  const isLoggedIn = false;

  return (
    <div>
      {isLoggedIn && <h1>Hello</h1>}
      {!isLoggedIn && <h1>Login Please</h1>}
    </div>
  );
};

export default Operator;

4.Switch 문 

여러 가지 조건이 필요할 때는 switch문을 사용할 수 있습니다.

import React from 'react';

const Switch = () => {
  const status = 'success';

  switch (status) {
    case 'loading':
      return <h1>loading...</h1>;
    case 'success':
      return <h1>성공!</h1>;
    case 'error':
      return <h1>오류 발생!</h1>;
    default:
      return null;
  }
};
export default Switch;

5. 함수로 조건부 렌더링

렌더리할 내용을 함수로 분리할 수 있습니다.

import React from 'react';

const Conditional = () => {
  const isLoggedIn = true; // or false

  const renderContent = () => {
    if (isLoggedIn) {
      return <h1>WelCome!</h1>;
    }
    return <h1>Please Login!</h1>;
  };
  return <div>{renderContent()}</div>;
};

export default Conditional;

 

 

GitHub - Koras02/react-bloging: https://thinky.tistory.com/category/Front-End/ReactJS

https://thinky.tistory.com/category/Front-End/ReactJS - Koras02/react-bloging

github.com

 

LIST

'Front-End > ReactJS' 카테고리의 다른 글

[ReactJS] 6장 폼  (0) 2025.02.25
[ReactJS] 5장 리스트와 키  (0) 2025.02.23
[React] 3장 이벤트 처리  (0) 2025.02.22
[ReactJS] 2장 컴포넌트와 UI 구성요소  (0) 2025.02.16
[ReactJS] 1장. React JS는 무엇인가?  (0) 2025.02.13