• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

header에서 a태그 들어간 후 해당 접속 중인 페이지 header a태그 색 바꾸기

22.02.15 18:11 작성 조회수 150

0

안녕하세요 제로초님 제가 Header 에 있는 a태그들을 지금 들어가 있는 페이지이라면? 

해당 a태그를 검정색으로 지정 해 주고 싶습니다.

제가 스타일컴포넌트를 이용하고 삼항 연산자를 이용 해 적용 했는데 반응 하지 않습니다.

왜 그럴까요 ㅠㅠ.

 


const Header = () => {

const location = useLocation();

const SLink = styled(Link)`
color: ${location.pathname ? "#4e5968" : "#000000"};
cursor: pointer;
`
console.log(location.pathname); // 순서 a링크 클릭 -> /order
return (
<>
<Headers>
<div>
<h1>제로초짱</h1>
<Ul>
<li>
<SLink to="/order">순서</SLink>
</li>
<li>
<SLink to="/">메인 페이지</SLink>
</li>
<li>
<SLink to="/rotationservice">환불</SLink>
</li>
</Ul>
</div>
</Headers>
</>
);
};

export default Header;

 

 

 

답변 1

답변을 작성해보세요.

1

저런 식으로 하시면 SLink가 계속 생성될뿐더러 원하는 타이밍에 값을 바꾸기 어려워집니다. 

<SLink pathname={location.pathname} to="/">...

이런 식으로 props로 전달하고 Header 바깥에서 SLink를 선언해서

cost SLink = styled(Link)`
  color: ${(props) => props.pathname ? '' : ''}
`;

const Header = ...

김수민님의 프로필

김수민

질문자

2022.02.16

선생님이 알려 주신 데로 해 봤는데 자꾸 에러가 납니다 ㅠㅠ 

<SLink pathname={location.pathname} to="/order">순서</SLink>

pathname 쪽에서 빨간색 밑줄이 뜨네요. 

{ children: string; pathname: string; to: string; }' 형식은 'IntrinsicAttributes & LinkProps & RefAttributes<HTMLAnchorElement> & { theme?: Theme | undefined; } & { ...; }' 형식에 할당할 수 없습니다.
'IntrinsicAttributes & LinkProps & RefAttributes<HTMLAnchorElement> & { theme?: Theme | undefined; } & { ...; }' 형식에 'pathname' 속성이 없습니다.
ts(2322)

 

SLink 를 선언 한 곳에서도 props pathname쪽에서 빨간색 밑줄이 나옵니다 

'LinkProps & RefAttributes<HTMLAnchorElement> & { theme?: Theme | undefined; } & { theme: Theme; }' 형식에 'pathname' 속성이 없습니다.ts(2339

 

const SLink = styled(Link)`
color: ${(props) => props.pathname ? "#4e5968" : "#000000"};
cursor: pointer;
text-decoration: none;
display: inline-block;
position: relative;
`
<SLink pathname={location.pathname} to="/order">순서</SLink>

styled(Link)<{ pathname?: string }>`

타입 선언도 같이 해보세요.

김수민님의 프로필

김수민

질문자

2022.02.16

했습니다. 하지만 모든 SLink 태그에서 전부 다 rgb(76, 194, 111)로 출력되네요. ㅠㅠ

지금 접속 한 페이지에서만 rgb색을 부여하고 아닌 페이지에서는 #4e5968을 부여해야 하는데.. 

const SLink = styled(Link)<{pathname?: string }>`
color: ${(props) => props.pathname ? "rgb(76, 194, 111)" : "#4e5968"};
cursor: pointer;
text-decoration: none;
display: inline-block;
position: relative;
`
 
 
<Ul>
<li>
<SLink pathname={location.pathname} to="/order">순서</SLink>
</li>
<li>
<SLink pathname={location.pathname} to="/">메인</SLink>
</li>
<li>
<SLink pathname={location.pathname} to="/rotationservice">환불</SLink>
</li>
</Ul>

애초에 그러면 location.pathname === '/order' 이런 비교문을 넣으셔야죠