ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • nextjs에서 svg 컴포넌트로 사용하는 방법
    Language/React 2024. 4. 4. 09:34

    컴포넌트 형태로 svg를 사용하려면?

     

    설치

    $ yarn add url-loader
    
    $ yarn add @svgr/webpack

     

    custom.d.ts

    declare module '*.mdx';
    
    declare module '*.svg' {
      const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
      const content: string;
    
      export { ReactComponent };
      export default content;
    }

     

    next.config.js

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      reactStrictMode: false,
      eslint: {
        // Warning: This allows production builds to successfully complete even if
        // your project has ESLint errors.
        ignoreDuringBuilds: true,
      },
      webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
        config.module.rules.push({
          test: /\.svg$/,
          use: ['@svgr/webpack', 'url-loader'],
        })
        return config
      },
    };
    module.exports = nextConfig;

     

     

    Sample

    import React, { useEffect, useState } from 'react';
    import { ReactComponent as CheckedIcon } from './assets/images/checkbox_icon_off.svg';
    import { ReactComponent as UncheckedIcon } from './assets/images/checkbox_icon_on.svg';
    
    interface CheckboxProps {
      className?: string;
      children?: React.ReactNode;
      checked: boolean;
      onChange: (checked: boolean) => void;
    }
    
    export const Checkbox: React.FC<CheckboxProps> = ({ ...props }) => {
      const [isChecked, setIsChecked] = useState(props.checked);
    
      const toggleCheckbox = () => {
        const theChecked = !isChecked;
        setIsChecked(theChecked);
        props.onChange(theChecked);
      };
    
      useEffect(() => {
        setIsChecked(props.checked);
      }, [props.checked]);
    
      return (
        <div onClick={toggleCheckbox} className={props.className}>
          {isChecked ? <CheckedIcon /> : <UncheckedIcon />}
          {/*{isChecked ? <img src="./assets/images/checkbox_icon_on.svg" /> : <img src="./assets/images/checkbox_icon_off.svg" />} */}
          {props.children}
        </div>
      );
    };
    
    ...

    댓글

Designed by Tistory.