FRONT/React

React 조건부 렌더링1 if

Tada.*+ 2021. 11. 9. 20:37
728x90

※ 조건부 렌더링 : 조건에 따라 다양한 컴포트 보여주기

- JavaScript와 같이 보여주기가 가능합니다.

 

1. if문 사용 방법

- 아래 두 개의 컴포넌트가 존재합니다.

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}

- isLoggedIn 변수의 boolean 값에 따라 'UserGreeting' 또는 'GuestGreeting' 컴포넌트가 보여집니다.

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />,
  document.getElementById('root')
);

- false 일 경우 결과 값 확인하기

false일 경우 결과 값 확인

- true일 경우 결과 값 확인하기

ReactDOM.render(
    <Greeting isLoggedIn={true} />,
    document.getElementById('root')
);

true일 경우 결과 값 확인

 

 

2. if 조건에 따른 엘리먼트 보여주기

// 추후 props에 전달할 onClickHandler 함수에서 Login여부를 체크하는 state를 변경하여,
// Login 여부에 따라 다른 컴포넌트(엘리먼트)를 보여줄 것입니다.
function LoginInButton(props) {
    return (
        <button onClick={props.onClickHandler}>
            LogIn
        </button>
    );
}

function LogOutButton(props) {
    return (
      <button onClick={props.onClickHandler}>
          LogOut
      </button>
    );
}
class LoginControl extends React.Component {
    constructor(props) {
        super(props);
        // 클래스 함수 바인딩
        this.handleLoginClick = this.handleLoginClick.bind(this);
        this.handleLogOutClick = this.handleLogOutClick.bind(this);
        this.state = {isLoggedin: false};
    }

    handleLoginClick() {
        this.setState({isLoggedin: true});
    }

    handleLogOutClick() {
        this.setState({isLoggedin: false});
    }

    render() {
        const isLoggedIn = this.state.isLoggedin;
        let button;
        // handler 함수에 의해 변경된 this.state.isLoggedin 값을 체크하여,
        // button 엘리먼트 설정
        if (isLoggedIn) {
            button = <LogOutButton onClickHandler={this.handleLogOutClick} />
        } else {
            button = <LoginInButton onClickHandler={this.handleLoginClick} />
        }

        return (
            <div>
                <Greeting isLoggedIn={isLoggedIn} />
                // 위에서 설정된 엘리먼트를 보여줌.
                {button}
            </div>
        );
    }
}
ReactDOM.render(
    <LoginControl />,
    document.getElementById('root')
);

화면 결과 보기

* 번외 : 바인딩이란? https://tadaiswhatever.tistory.com/20?category=1055903

 

이전 글 : 2021.11.08 - [UI/React] - React Event 처리 시 주의사항 / React 이벤트 처리 시 주의사항

 

React Event 처리 시 주의사항 / React 이벤트 처리 시 주의사항

※ 주의사항 * JSX 콜백 안에서 this를 사용할 경우에 주의해야 합니다. 1. Bind 사용 - bind를 해주기 전과 후의 차이점 아래 코드 중 'this.handleClick = this.handleClick.bind(this);'에 집중해 주세요. con..

tadaiswhatever.tistory.com

다음 글 : 2021.11.10 - [UI/React] - React 조건부 렌더링2 논리 연산자

 

React 조건부 렌더링2 논리 연산자

※ 조건부 렌더링 : 조건에 따라 다양한 컴포트 보여주기 조건부 렌더링1 : https://tadaiswhatever.tistory.com/21 1. 논리 연산자 사용 방법 - { 조건 && 엘리먼트} function Sample(props) { const unreadMess..

tadaiswhatever.tistory.com

 

728x90