React에서 자주 쓰는 if문 패턴

LikeChoonsik's·2022년 1월 31일
0

React

목록 보기
1/9
post-thumbnail

1.컴포넌트 속 JSX를 조건부로 보여주고 싶을때

const 컴포넌트 = () => {
if(true){
return <div></div>
} else{
return null
}
}

2.삼항연산자

자주쓰는 간단한 if문

const 컴포넌트 = () => {
  return (
    <div>
      {
        1 === 1
        ? <p>짜잔</p>
        : null
      }
    </div>
  )
} 

물론 삼항연산자는 중첩사용도 가능하나 그렇게 쓸꺼면 다른 방식으로 작성합시다.

3.&& 연산자

if문 쓸 때 만약 참이면 ~이거보여주고 아니면 null해주셈 할 때 삼항연산자 대신 보기 좋게 &&연산자 사용 추천

const 컴포넌트 = () => {
  return (
    <div>
      {
        1 === 1 && <p>짜잔</p>
      }
    </div>
  )
} 

이경우 조건식이 true일 때 보일 값을 작성만 해주면 끝!

4. switch/case 조건문

if문을 연달아 많이 사용할때 사용하여 코드를 줄 일 수 있습니다
예시로 redux reducer쓸 때 생각해보면

function reducer(state, action){
  
  if (action.type === 'addProuduct'){
    return addState
  } else if (action.type === 'removeProduct'){
    return removeState
  } else {
    return state
  }
}

이렇게 쓸 껄

function reducer(state, action){
  
  switch (action.type) {
    case 'addProduct' :
      return addState;
    case 'removeProduct' : 
      return removeState;
    default : 
      return state
  }

}

이렇게 사용 가능
사용법은
1)switch (검사할변수명){} 작성
2)case 검사할변수명이 일치하는지 : 작성
3)일치시 case 밑에 코드 실행
4)default : 는 맨 마지막 else문과 동일

5. 오브젝트 자료형을 응용 enum

경우에 따라서 다른 HTML을 보여주고 싶은 경우 사용

const 컴포넌트 = () => {
  const [current, setCurrent] = useState('info');
  return (
    <div>
      {
        { 
           info : <p>정보</p>,
           shopping : <p>쇼핑</p>,
           refund : <p>환불</p>
        }[current]
      }

    </div>
  )
} 

예시로 이런 경우가 있다면 지금 예시는
objec{} 뒤에 [] 대괄호를 붙여서 "key값이 current인 자료를 보여주세요"라고 나타내고 있습니다

이런 경우 current라는 state값을 변경 시키는 것만으로 원하는 HTML을 보여줄 수 있습니다. 좀 더 코드를 깔끔히 정리하면

let innerText = {
	info : <p>정보</p>,
    shopping : <p>쇼핑</p>,
    refund : <p>환불</p>
}

const 컴포넌트 = () => {
  const [current, setCurrent] = useState('info');
  return (
    <div>
      {
		innerText[current]
      }
    </div>
  )
} 

이렇게 축약 가능합니다

profile
춘식이는 너무 귀엽습니다.

0개의 댓글