본문 바로가기
내마음대로만들어보자/React 프로젝트 만들기 이해

[React]로그인 상태에 따른 분기 하기

by 소농민! 2021. 11. 28.
728x90

1. 로그인한 상태일때 헤더 만들기

import React from "react";
import {Grid, Text, Button} from "../elements";

const Header = (props) => {

    const [is_login, setIsLogin] = React.useState(false);
    if(is_login){
        return (
          <React.Fragment>
            <Grid is_flex padding="4px 16px">
              <Grid>
                <Text margin="0px" size="24px" bold>
                  헬로
                </Text>
              </Grid>

              <Grid is_flex>
                <Button text="내정보"></Button>
                <Button text="알림"></Button>
                <Button text="로그아웃"></Button>
              </Grid>
            </Grid>
          </React.Fragment>
        );
    }
    return (
        <React.Fragment>
            <Grid is_flex padding="4px 16px">
                <Grid>
                    <Text margin="0px" size="24px" bold>헬로</Text>
                </Grid>
                
                <Grid is_flex>
                    <Button text="로그인"></Button>
                    <Button text="회원가입"></Button>
                </Grid>
            </Grid>
        </React.Fragment>
    )
}

Header.defaultProps = {}

export default Header;

2. 쿠키가 있으면 로그인한 헤더 보여주기

import React from "react";
import {Grid, Text, Button} from "../elements";
import {getCookie, deleteCookie} from "../shared/Cookie";
const Header = (props) => {

    const [is_login, setIsLogin] = React.useState(false);

    React.useEffect(() => {

        // 쿠키를 가져오기
        let cookie = getCookie('쿠키 이름 넣기!');
        // 확인
        console.log(cookie);
        // 쿠키가 있으면?
        if(cookie){
            setIsLogin(true);
        }else{
            setIsLogin(false);
        }
    });

    if(is_login){
        return (
          <React.Fragment>
            <Grid is_flex padding="4px 16px">
              <Grid>
                <Text margin="0px" size="24px" bold>
                  헬로
                </Text>
              </Grid>

              <Grid is_flex>
                <Button text="내정보"></Button>
                <Button text="알림"></Button>
                <Button text="로그아웃"></Button>
              </Grid>
            </Grid>
          </React.Fragment>
        );
    }
    return (
        <React.Fragment>
            <Grid is_flex padding="4px 16px">
                <Grid>
                    <Text margin="0px" size="24px" bold>헬로</Text>
                </Grid>
                
                <Grid is_flex>
                    <Button text="로그인"></Button>
                    <Button text="회원가입"></Button>
                </Grid>
            </Grid>
        </React.Fragment>
    )
}

Header.defaultProps = {}

export default Header;