- Notifications
You must be signed in to change notification settings - Fork2
An easy and bundler agnostic way to use a sprite-sheet for your svgs. With server side rendering in mind
License
kaoDev/react-lazy-svg
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The easy way to use SVG sprite-sheets
react-lazy-svg is a simple way to use SVGs with the performance benefits of asprite-sheet and svg css styling possibilities. Without bloating the bundle. Itautomatically creates a sprite-sheet for all used SVGs on the client but alsoprovides a function to create a server side rendered sprite-sheet for icons usedin the first paint. So you can inject the critical svg
npm install --save react-lazy-svg
Examples on how to use react-lazy-svg with remix and next.js can be found in the./example-nextjs/ and./example-remix/directory.
Wrap the App with the contextProvider and provide a function to resolve SVGstrings by URL. If you are using server side rendering you should also callinitOnClient()
to hydrate the sprite sheet context.
import{SpriteContextProvider,initOnClient.Icon}from'react-lazy-svg';importicon1from'./icon1.svg';constloadSVG=async(url:string)=>{returnawait(awaitfetch(url)).text();};initOnClient();constRoot=()=>(<SpriteContextProviderloadSVG={loadSVG}><Iconurl={icon1}className="icon"></Icon><Iconurl={icon1}className="icon red"></Icon></SpriteContextProvider>);
On the server the SVG resolver function could look like this, and load the svgcontents from the file system.
constsvgIconFiles=newMap<string,string>();constreadFile=promisify(fs.readFile);constcdnBase='http://localhost:3001/static/media/';exportconstreadSvg=async(url:string)=>{if(svgIconFiles.has(url)){returnsvgIconFiles.get(url);}if(url.startsWith(cdnBase)){url=path.join(process.cwd(),url.replace(cdnBase,'./build/public/static/media/'),);constsvgString=awaitreadFile(url,{encoding:'utf8'});svgIconFiles.set(url,svgString);returnsvgString;}returnundefined;};
About
An easy and bundler agnostic way to use a sprite-sheet for your svgs. With server side rendering in mind
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.