Notice
Recent Posts
Recent Comments
Link
250x250
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- window 정책변경
- 그누보드반응형
- legacy-peer
- 단어단위로떨어지기
- 동적객체
- MediaQuery
- 아이콘사용법
- react npm install
- maxwidth
- npm start
- slickslider
- node설치
- node 오류
- 플러그인
- git lab clone
- minwidth
- 의존성문제
- vscode git clone
- 웹아이콘
- 정적객체
- owlcarousel
- 글자들여쓰기
- XEIcon
- npm install
- Git clone
- googleicon
- package.json
- fontawesome
- npm install 문제
- 이미지반응형
Archives
- Today
- Total
어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ
React useEffect로 body class넣기 / 리팩토링 본문
728x90
🤔 처음에는 로그인 페이지만 분리해서 이렇게 적음
useEffect(() => {
const isLogin = location.pathname === '/login';
if(isLogin){
document.body.classList.add('login_page');
}
}, [location.pathname]);
🤔 근데 점점 분기처리할 게 생겨서 일단 저 방식으로 추가하고
리팩토링을 어떻게 해야할지 생각해 봄
useEffect(() => {
const isLogin = location.pathname === '/login';
const isPasswordFind = location.pathname === '/PasswdReset';
const isChangeCompany = location.pathname === '/change-company';
document.body.classList.remove('login_page', 'password_page', 'change_company_page');
if(isLogin){
document.body.classList.add('login_page');
}
if(isPasswordFind){
document.body.classList.add('password_page');
}
if(isChangeCompany){
document.body.classList.add('change_company_page');
}
}, [location.pathname]);
🔖👩💻 리팩토링
** map 기반 정리
useEffect(() => {
const pathClassMap = {
'/login': 'login_page',
'/PasswdReset': 'password_page',
'/change-company': 'change_company_page',
};
const className = pathClassMap[location.pathname];
document.body.classList.remove(...Object.values(pathClassMap));
if (className) {
document.body.classList.add(className);
}
}, [location.pathname]);
👩💻 document.body.classList.remove(...Object.values(pathClassMap));
=>
Object.values(pathClassMap);
// ['login_page', 'password_page', 'change_company_page']
👉 객체의 value만 배열로 추출
=> class 이름으로 넣을 부분만 추출하여 삭제시킨다 (유지보수 좋음)
=> 각 class를 추가할 경우 누락시키는 경우도 있기 때문
다른 방법으로는 route 정보를 상수 객체로 분리하는 것도 고려했으나,
다른 파일에서 재사용하지 않고 분기 페이지 수가 적어서 map 기반으로만 리팩토링
728x90
'개발 > 🟦 React' 카테고리의 다른 글
| [FE] type.maybe, maybeNull (0) | 2026.01.07 |
|---|---|
| [FE] MST란? React_MobX State Tree (0) | 2026.01.07 |
| ReactSortable 드래그, 솔팅 기능_리액트 라이브러리 (0) | 2025.12.31 |
| 다국어 처리 useTranslation() 훅 사용 (0) | 2025.12.03 |
| useRef로 resize width 계산 후 class 넣기 (0) | 2025.12.01 |
Comments
