-
[React] 다섯종류의 조건부 렌더링Java Script & Type Script 2023. 3. 21. 11:28728x90
1. 컴포넌트 안에서 쓰는 if/else
function Component() { if ( true ) { return <p>참이면 보여줄 HTML</p>; } else { return null; } }
위 내용은 다음과 동일한 결과를 가져온다.function Component() { if ( true ) { return <p>참이면 보여줄 HTML</p>; } return null; }
else를 생략해도 똑같은 기능을 한다.
JS는 function안에서 return이라는 키워드를 만나면 return 밑에있는 코드는 더이상 실행되지 않음.
2. 삼항연산자 Ternary operator
-> 중첩사용도 된다.function Component() { return ( <div> { 1 === 1 ? <p>참이면 보여줄 HTML</p> : ( 2 === 2 ? <p>안녕</p> : <p>반갑</p> ) } </div> ) }
3. &&연산자
내가 이번 프로젝트에서 처음 활용법을 깨달았던 &&연산자!
챗 gpt야 고마워
true && '안녕';
false && '안녕';
true && false && '안녕';
맨 윗 코드는 '안녕'이 남고
중간 코드는 false가 남고
맨 아래 코드는 false가 남습니다.
자바스크립트는 그냥 &&로 연결된 값들 중에 처음 등장하는 falsy 값을 찾아주고 그게 아니면 마지막값을 남겨준다function Component() { return ( <div> { 1 === 1 && <p>참이면 보여줄 HTML</p> } </div> ) }
왼쪽 조건식이 true면 오른쪽 JSX가 그 자리에 남습니다.
왼쪽 조건식이 false면 false가 남습니다.
(false가 남으면 HTML로 렌더링하지 않습니다)
4. switch/case 조건문
if문이 중첩해서 여러개 달려있는 경우function Component2(){ const user = 'seller'; switch (user){ case 'seller' : return <h4>판매자 로그인</h4> case 'customer' : return <h4>구매자 로그인</h4> default : return <h4>그냥 로그인</h4> } }
1. switch (검사할변수){} 이거부터 작성하고
2. 그 안에 case 검사할변수가이거랑일치하냐 : 를 넣어줍니다.
3. 그래서 이게 일치하면 case : 밑에 있는 코드를 실행해줍니다.
4. default :는 그냥 맨 마지막에 쓰는 else문과 동일합니다.
5. object/array 자료형 응용functon Component(){ let 현재탭 ="info"; return ( <div> { { info: <p>상품정보</p>, shipping: <p>배송정보</p>, refund: <p>환불약관</p> }[현재탭] } </div> ) }
728x90'Java Script & Type Script' 카테고리의 다른 글
[React] 게시글 최신순 정렬 구현 useState & 쿼리스트링 ( useReducer써보기) (0) 2023.04.08 [Refactor] Gnims 코드 리팩토링 with Chat GPT (0) 2023.03.22 [React] 리덕스 초기 세팅, 리듀서만들기 복습 (0) 2023.03.21 43. Ajax- Axios, Promise.all, fetch함수 복습하기 (0) 2023.03.18 [React] 컴포넌트의 Lifecycle [useEffect에대한 고찰 2] 컴포넌트야 인생 원래 그런거야 (0) 2023.03.18