ㅇㅇㅈ Blog

프론트엔드 수행중

0%

Final-Project-2

Final-Project-02

2022.07.06

스타일 작업을 하는중..
스타일드 컴포넌트로 테마설정도 하고…
switch case로 클릭하는거에 따라 보기타입이 바뀌게도 설정 해 줄 수 있다

나중에 코드 정리해야지

일단 지금은 카테고리 버튼을 누르면 페이지가 이동되고
이동된 페이지에 상단에 클릭된 버튼이 활성화 되어 있다

문제는 버튼들이 가로로 나열되어있고 overflow scroll인데

마지막 카테고리를 클릭하면 스크롤하기 전에 해당 버튼이 활성화 된게 안 보인다는 점..

일단 아이디어는 주소로 넘어오는 params와
버튼의 id를 비교해서 같으면 색상을 활성화 해주는거다

그래서 검색 시작

useRef 와 scrollIntoView 라는걸 사용하면 클릭하면 참조값에 스크롤이 된다고 해서 작성 해봤다.

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
const CategoryButton = () => {
const params = useParams();
const btnRef = useRef(null);

useEffect(() => {
btnRef.current.scrollIntoView({
behavior: "smooth",
});
}, []);

return (
<QuickButtonWrap id="scroll-container">
{mainCategory.map((category) => {
return (
<RadiusButton
orange={params.id === category.id}
ref={btnRef}
>
{category.category}
</RadiusButton>
);
})}
</QuickButtonWrap>
);
};

export default CategoryButton;

이렇게 작성했더니 맵을 돌면서 마지막 버튼에만 활성이 되는 것이다

근데 여럿 찾아본 블로그와 다른 점은.. 블로그에서는 ref를 부모로부터 받아와 참조를 하는거지만
여기서는 그렇지가 않다 부모 자식 관계도 아니기 때문에….

그리고 다시 폭풍 검색

찾다보니 ref를 배열로 저장할 수 있더라

1
ref={(el) => (btnRef.current[idx] = el)}

이런식인데
맵을 돌면서 index값으로 current를 찾아 내는 방식인거 같다!?

그래서 일단 배열로 저장하고 콘솔로 찍어 보았다.

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
const CategoryButton = () => {
const params = useParams();
const btnRef = useRef([]); // 배열로 설정

useEffect(() => {
btnRef.current.scrollIntoView({
behavior: "smooth",
});
}, []);

return (
<QuickButtonWrap id="scroll-container">
{mainCategory.map((category,idx) => {
return (
<RadiusButton
orange={params.id === category.id}
ref={(el) => (btnRef.current[idx] = el)} // ref를 배열로 저장
>
{category.category}
</RadiusButton>
);
})}
</QuickButtonWrap>
);
};

export default CategoryButton;

각 버튼의 ref가 배열로 저장된다.

그럼 이제 btnRef를 for문을 돌면서 해당 인덱스에 있는 텍스트와 params를 비교해서
scrollIntoView를 해주면 된다.

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
32
33
34
35
36
37
const CategoryButton = () => {
const params = useParams();
const btnRef = useRef([]);

useEffect(() => {
btnRef.current.forEach((item, idx) => { // 배열을 순회하고
if (item.innerText.toLowerCase() === params.id) { // innertext와 비교를 했다..
btnRef.current[idx].scrollIntoView({ // true 일시 해당 index의 ref로 scrollIntoView가 된다
behavior: "smooth",
});
}
});
}, []);

return (
<QuickButtonWrap id="scroll-container">
{mainCategory.map((category, idx) => {
return (
<Link
to={`/quick${category.path}`}
key={category.id}
id={category.id}
>
<RadiusButton
orange={params.id === category.id}
ref={(el) => (btnRef.current[idx] = el)}
>
{category.category}
</RadiusButton>
</Link>
);
})}
</QuickButtonWrap>
);
};

export default CategoryButton;

잘 작동 된다!