今日已更新 138 条资讯 | 累计 26942 条内容
关于我们

How to Use SVG Icons in React, Next.js, and Tailwind CSS

Svg/icons 2026年08月02日 05:24 0 次阅读 来源:Dev.to

There are exactly three sensible ways to get an SVG icon into a React codebase: paste it inline as a component, import the file through a build transform like SVGR, or reference it from a sprite. Most projects need only the first. This guide walks through the inline approach with Next.js and Tailwind specifics, and points to the deeper guides where a topic deserves its own article. Option 1: an inline JSX component Take a real icon from the catalog, convert the SVG attributes to JSX casing, and you have a dependency-free component. This is Lucide's search icon, exactly as it ships in the Lucide set , wrapped for React: export function SearchIcon ( props ) { return ( < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 24 24" fill = "none" stroke = "currentColor" strokeLinecap = "round" strokeLinejoin = "round" strokeWidth = { 2 } aria-hidden = "true" { ... props } > < path d = "m21 21l-4.34-4.34" /> < circle cx = "11" cy = "11" r = "8" /> </ svg > ); } The JSX gotchas are all attribute casing: stroke-width becomes strokeWidth , stroke-linecap becomes strokeLinecap , and class becomes className . Icon pages on this site do the conversion for you: every icon offers React, Vue, Svelte, and Solid snippets next to the raw SVG, so you can copy the JSX form directly. If you have a folder of SVG files instead, the free SVG to component converter batch-converts them in the browser. Prefer importing .svg files over pasting? That is the SVGR route, covered step by step in our React with Vite and SVGR guide . Next.js: server components by default An icon component like the one above has no state, no effects, and no event handlers, which makes it a perfect React Server Component. In the Next.js App Router it renders to static markup on the server and adds nothing to the client bundle: import { SearchIcon } from " @/components/icons " ; export default function DocsHeader () { return ( < label className = "flex items-center gap-2" > < SearchIcon className = "h-5 w-5 text-zinc

本文内容来源于互联网,版权归原作者所有
查看原文