props로 조건부 렌더링이 가능하다.
📍 검색 창 입력값 존재 여부에 따라 해당 요소의 border-radius 값을 다르게 주고 싶을 때:
1. 검색 창 입력값 존재 여부에 따라 ture, false를 가지는 hasText 라는 변수로 상태 관리를 해준다.
2. 컴포넌트에 hasText를 props로 내려보낸다.
3. 다음과 같이 border-radius 값을 조건부 렌더링으로 걸어준다.
border-radius: ${(props) =>
props.hasText ? activeBorderRadius : inactiveBorderRadius};
이렇게 하면 입력값이 있을 때, 즉 hasText가 true일 때 컴포넌트의 class명을 삼항연산자로 다르게 줘서 css 코드를 별도로 적어주는 것보다 더 간편하게 처리할 수 있다.


🔽 props를 내려보낸 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const activeBorderRadius = "1rem 1rem 0 0"; | |
const inactiveBorderRadius = "1rem 1rem 1rem 1rem"; | |
const InputContainer = styled.div` | |
border-radius: ${(props) => | |
props.hasText ? activeBorderRadius : inactiveBorderRadius}; | |
` | |
export const Autocomplete = () => { | |
const [hasText, setHasText] = useState(false); | |
const [inputValue, setInputValue] = useState(""); | |
useEffect(() => { | |
if (inputValue === "") { | |
setHasText(false); | |
} | |
}, [inputValue]); | |
const handleInputChange = (event) => { | |
setInputValue(event.target.value); | |
setHasText(true); | |
}; | |
return ( | |
<div className="autocomplete-wrapper"> | |
<InputContainer hasText={hasText}> | |
<input | |
value={inputValue} | |
onChange={handleInputChange} | |
/> | |
</InputContainer> | |
{hasText ? ( | |
<DropDown | |
options={options} | |
handleComboBox={handleDropDownClick} | |
currentOption={currentOption} | |
/> | |
) : null} | |
</div> | |
); | |
} |
🔽 class 이름을 다르게 주는 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 위의 코드와 겹치는 부분은 생략 | |
const InputContainer = styled.div` | |
border-radius: ${inactiveBorderRadius}; | |
&.hasText { | |
border-radius: ${activeBorderRadius}; | |
} | |
` | |
export const Autocomplete = () => { | |
return ( | |
<InputContainer className={hasText ? "hasText" : ""}> | |
</InputContainer> | |
); | |
}; |
'배워서 남 주자' 카테고리의 다른 글
[JavaScript] 숫자 100000을 100,000으로 바꾸는 방법 (0) | 2023.01.03 |
---|---|
CLI로 github pages를 사용해 웹사이트 배포하는 방법 (0) | 2023.01.03 |
[알고리즘] 2 x n 보드 타일링과 피보나치 수열 (0) | 2022.12.30 |
배열 map 메소드 활용법 (0) | 2022.12.29 |
input 엔터키 입력 감지해서 이벤트 실행하는 방법 (0) | 2022.12.26 |