React Image Webp
Features
- Rendering image in WebP format if browser supports.
- Server-side rendering using React Context
- Written on Typescript
Note: as of January, 2019 only 72.59% supports WebP format (caniuse.com)
Installation
Using npm:
npm i react-img-webp
Usage
For runtime webp checking:
; const jpg = "https://cdn.horatius.pro/image.jpg";const webP = "https://cdn.horatius.pro/image.webp"; const Component = <Image src=jpg webP=webP />; const isBrowserSupportWebP = ; // if you want to detect webP support in other places
Server-side rendering
Library supports rendering webP on server-side.
All you need to pass Accept
header value to context controller.
; // it may be any http requestconst request = headers: Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" const jpg = "https://cdn.horatius.pro/image.jpg";const webP = "https://cdn.horatius.pro/image.webp"; const Component = { return <ContextWebPController accept=requestheadersAccept> <ContextImage src=jpg webP=webP /> </ContextWebPController> }
For inline styles (background-image etc.)
You may use context manually to render any element instead of <img>
:
;; const img = src: webP: ; const Icon: React.FunctionComponent = <ContextWebPConsumer> <i className="icon" style= backgroundImage: `url()` /> </ContextWebPConsumer>;