Next.js에서 svg에 styled-components 적용

이춘구·2022년 6월 9일
0

svgr 설치

yarn add -D @svgr/webpack

next.config.js 수정

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    });

    return config;
  },
};

module.exports = nextConfig;

svg 파일 수정

width, height, fill, stroke 등 변경을 원하는 속성값을 current로 수정

<svg width="current" height="current" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M12.889 28.4445C13.6254 28.4445 14.2223 27.8475 14.2223 27.1112C14.2223 26.3748 13.6254 25.7778 12.889 25.7778C12.1526 25.7778 11.5557 26.3748 11.5557 27.1112C11.5557 27.8475 12.1526 28.4445 12.889 28.4445Z" fill="current" stroke="current" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  <path d="M25.3333 28.4445C26.0697 28.4445 26.6667 27.8475 26.6667 27.1112C26.6667 26.3748 26.0697 25.7778 25.3333 25.7778C24.597 25.7778 24 26.3748 24 27.1112C24 27.8475 24.597 28.4445 25.3333 28.4445Z" fill="current" stroke="current" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  <path d="M2.66675 2.6665H7.51523L10.7637 18.5357C10.8746 19.0814 11.1782 19.5715 11.6213 19.9204C12.0645 20.2692 12.6191 20.4545 13.188 20.4438H24.9698C25.5386 20.4545 26.0932 20.2692 26.5364 19.9204C26.9796 19.5715 27.2832 19.0814 27.394 18.5357L29.3334 8.59229H8.72735" stroke="current" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

styled-components 적용 & 사용

// svg를 컴포넌트 import하듯이 import
import Cart from '/public/images/icon-shopping-cart.svg';

// styled-components의 확장 기능을 사용해서 svg 스타일링
const CartIcon = styled(Cart)`
  path {
    stroke: blue;
  }
  &:hover {
    path {
      stroke: red;
    }
  }
`;

const NavBar = () => {
  return (
    <nav>
      <CartIcon width={32} height={32} />
    <nav>
  );
};

export default NavBar;

결과

Reference

https://react-svgr.com/docs/next/
https://styled-components.com/docs/basics#extending-styles

profile
프런트엔드 개발자

0개의 댓글