-
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> ); }; ...
'Language > React' 카테고리의 다른 글
Toast 만들기 (0) 2024.07.09 nextJS 사용하는 iOS 단말기에서 뒤로가기 페이지 흰색 이슈 (0) 2024.06.20 react-hook-form typescript로 변환 및 컴포넌트 생성 (antd) (0) 2023.12.27 react에 typescript 적용하기 (1) 2023.12.27 react-hook-form 적용기 (antd) (0) 2023.12.18