This is a quick start guide to show how to integrate ImageKit in a React application using the ImageKit React SDK. The code samples covered here are hosted on Github.
This guide walks you through the following topics:
- Setting up ImageKit React SDK
- Rendering images
- Setting the ImageKit context for the SDK
- Applying common image manipulations
- Adding overlays
- Lazy loading images
- Blurred image placeholder
- Client-side file uploading
- Advanced file uploading
- Rendering videos
Setup ImageKit React SDK
For this tutorial, we are creating a dummy React app.
Create a React app:
Let's use the create-react-app
CLI utility provided by React to build a new project:
npx create-react-app imagekit-react-app
Navigate to the project directory:
cd imagekit-react-app/
Open up the project in your text editor of choice, and navigate to src/App.js
. This is where we will do most of our work. It should look like this:
import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;
Now run the app:
npm start
In your web browser, navigate to http://localhost:3000/
You should see the dummy app created by React CLI. Now, we can begin our work.
Install the ImageKit React SDK:
Installing the ImageKit React SDK in our app is pretty simple:
npm install --save imagekitio-react
Initialize the React SDK
Before the SDK can be used, let's learn about and obtain the requisite initialization parameters:
urlEndpoint
is a required parameter. This can be obtained from the URL endpoint section or the developer section on your ImageKit dashboard.publicKey
andauthenticator
parameters are optional and only needed if you want to use the SDK for client-side file upload.publicKey
can be obtained from the Developer section on your ImageKit dashboard.authenticator
expects an asynchronous function that resolves with an object containing the necessary security parameters, i.e., signature, token, and expiration.
// required parameter to fetch images const urlEndpoint = '<YOUR_IMAGEKIT_URL_ENDPOINT>'; // optional parameters (needed for client-side upload) const publicKey = '<YOUR_IMAGEKIT_PUBLIC_KEY>'; const authenticator = ()=>{ return new Promise((resolve,reject)=>{ resolve({signature,token,expiry}) }) };
Do not include your API private key in any client-side code, including this SDK or its initialization. If you pass the privateKey
parameter while initializing this SDK, it will throw an error.
ImageKit Components:
This SDK provides 3 components:
IKImage
for image rendering. The output is a<img>
tag.IKVideo
for video resizing. This renders a<video>
tag.IKUpload
for file uploading. The output is a<input type="file">
tag.IKContext
for defining authentication context, i.e.urlEndpoint
,publicKey
andauthenticator
to all child elements.
You can import components individually:
import { IKImage, IKVideo, IKContext, IKUpload } from 'imagekitio-react';
Configure the app for ImageKit
Let's remove the existing dummy code in src/App.js
file, then add the urlEndpoint
:
import React from 'react'; import './App.css'; const urlEndpoint = '<YOUR_IMAGEKIT_URL_ENDPOINT>'; function App() { return ( <div className="App"> </div> ); } export default App;
Rendering images
Loading image from relative path:
Remember the default image we mentioned earlier? It should be available at the following URL:
https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/default-image.jpg
Let's fetch and display it! For this, we will use the IKImage
component.
Import IKImage
from the SDK:
import { IKImage } from 'imagekitio-react';
Now let's add it to our App
. Along with the image path
prop, it also needs the prop for urlEndpoint
:
<IKImage urlEndpoint={urlEndpoint} path="default-image.jpg" />
Rendered HTML element:
<img src="https://ik.imagekit.io/demo/default-image.jpg?ik-sdk-version=react-1.x.x" alt="">
The App.js
file should look like this now:
import React from 'react'; import './App.css'; import { IKImage } from 'imagekitio-react'; const urlEndpoint = '<YOUR_IMAGEKIT_URL_ENDPOINT>'; function App() { return ( <div className="App"> <h1>ImageKit React quick start</h1> <IKImage urlEndpoint={urlEndpoint} path="default-image.jpg" /> </div> ); } export default App;
Your React app should now display the default image in its full size:
You can pass styles and other attributes as props. For e.g. lets add 400px width_ _by adding the width
prop:
<IKImage urlEndpoint={urlEndpoint} path="default-image.jpg" width="400" />
This is how the output should look now:
Note that here we have set the width to 400px at the <img>
tag level only. Intrinsically, the fetched image is still 1000px wide.
Loading image from an absolute path:
If you have an absolute image path coming from the backend API e.g. https://www.custom-domain.com/default-image.jpg
then you can use src
prop to load the image.
For example:
<IKImage urlEndpoint={urlEndpoint} src="https://ik.imagekit.io/demo/default-image.jpg" width="400" />
The output looks like this:
Setting ImageKit context for the SDK
It is not necessary to specify the urlEndpoint
in every instance of IKImage
. This can be managed much more easily with the IKContext
component.
IKContext
is a wrapper that can be configured with your SDK initialization parameters. Pass your urlEndpoint
to it as a prop, and you're good to go!
Let's go ahead and import it within the App.js
file:
import { IKContext, IKImage } from 'imagekitio-react';
Now add the IKContext
component to the render function:
<IKContext urlEndpoint={urlEndpoint}></IKContext>
Let's nest our IKImage
components within it, so that those can access the urlEndpoint
from the context wrapper.
import React from 'react'; import './App.css'; import { IKContext, IKImage } from 'imagekitio-react'; const urlEndpoint = '<YOUR_IMAGEKIT_URL_ENDPOINT>'; function App() { return ( <div className="App"> <IKContext urlEndpoint={urlEndpoint}> <h1>ImageKit React quick start</h1> <IKImage path="default-image.jpg" width="400" /> <h2>Loading image from an absolute path</h2> <IKImage src="https://ik.imagekit.io/demo/default-image.jpg" width="400" /> </IKContext> </div> ); } export default App;
Basic image manipulation
Let’s now learn how to manipulate images using transformations.
The React SDK gives a name to each transformation parameter, e.g. height
for h
and width
for w
parameter. It makes your code more readable. If the property does not match any of the available options, it is added as it is. See the full list of supported transformations in React SDK on Github.
You can also use h
and w
parameter instead of height
and width
.
Height and width manipulation
To resize an image along with its height or width, we need to pass the transformation
object as a prop to IKImage
.
Let’s resize the default image to 200px height and width:
<IKImage path="default-image.jpg" transformation={[{ height: 200, width: 200 }]} />
Rendered HTML element:
<img src="https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/tr:h-200,w-200/default-image.jpg?ik-sdk-version=react-1.x.x" path="default-image.jpg" alt="">
Refresh your browser to get the resized image.
Quality manipulation
You can use the quality parameter to change image quality like this:
<IKImage path="default-image.jpg" transformation={[{ quality: 10 }]} width="400" />
Rendered HTML:
<img src="https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/tr:q-10/default-image.jpg?ik-sdk-version=react-1.x.x" path="default-image.jpg" width="400" alt="">
Crop mode
Let’s now see how cropping works. We will try the extract
crop strategy. In this strategy, instead of resizing the whole image, we extract out a region of the requested dimension from the original image.
<IKImage path="default-image.jpg" transformation={[{ height: 300, width: 200, cropMode: 'extract', }]} />
Rendered HTML element:
<img src="https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/tr:h-300,w-200,cm-extract/default-image.jpg" path="default-image.jpg" alt="">
Chained transformation
Chained transformations provide a simple way to control the sequence in which transformations are applied.
Let’s try it out by resizing an image, then rotating it:
<IKImage path="default-image.jpg" transformation={[{ height: 300, width: 200 }]} />
Transformation URL:
<img src="https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/tr:h-300,w-200/default-image.jpg" path="default-image.jpg" alt="">
Now, rotate the image by 90 degrees.
<IKImage path="default-image.jpg" transformation={[{ height: 300, width: 200, }, { rt: 90, }]} />
Chained Transformation URL:
<img src="https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/tr:h-300,w-200:rt-90/default-image.jpg" path="default-image.jpg" alt="">
Let’s flip the order of transformation and see what happens.
<IKImage path="default-image.jpg" transformation={[{ rt: 90, }, { height: 300, width: 200, }]} />
Chained Transformation URL:
<img src="https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/tr:rt-90:h-300,w-200/default-image.jpg" path="default-image.jpg" alt="">
Adding overlays
ImageKit.io enables you to apply overlays to images and videos using the raw parameter with the concept of layers. The raw parameter facilitates incorporating transformations directly in the URL. A layer is a distinct type of transformation that allows you to define an asset to serve as an overlay, along with its positioning and additional transformations.
Text as overlays
You can add any text string over a base video or image using a text layer (l-text).
For example:
<IKImage path="/default-image.jpg" transformation={[{ "width": 400, "height": 300 },{ "raw": "l-text,i-Imagekit,fs-50,l-end" }]} />
Sample Result URL
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-text,i-Imagekit,fs-50,l-end/default-image.jpg
Output Image:
Image as overlays
You can add an image over a base video or image using an image layer (l-image).
For example:
<IKImage path="/default-image.jpg" transformation={[{ "width": 400, "height": 300 },{ "raw": "l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end" }]} />
Sample Result URL
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end/default-image.jpg
Output Image:
Solid color blocks as overlays
You can add solid color blocks over a base video or image using an image layer (l-image).
For example:
<IKVideo path="/img/sample-video.mp4" transformation={[{ "width": 400, "height": 300 },{ "raw": "l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end" }]} />
Sample Result URL
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end/img/sample-video.mp4
Output Image:
Lazy-loading images in React
You can lazy load images using the loading
prop in IKImage
component. When you use loading="lazy"
, all images that are immediately viewable without scrolling load normally. Those that are far below the device viewport are only fetched when the user scrolls near them.
The SDK uses a fixed threshold based on the effective connection type to ensure that images are loaded early enough so that they have finished loading once the user scrolls near to them.
You should always set the height and width of the image element to avoid layout shift when lazy-loading images.
<IKImage path="default-image.jpg" transformation={[{ height: 300, width: 400 }]} loading="lazy" height="300" width="400" />
Rendered HTML element:
<img src="https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/tr:h-300,w-400/default-image.jpg?ik-sdk-version=react-1.x.x" path="default-image.jpg" loading="lazy" height="300" width="400" alt="">
Blurred image placeholder
To improve user experience, you can use a low-quality blurred variant of the original image as a placeholder while the original image is being loaded in the background. Once the loading of the original image is finished, the placeholder is replaced with the original image.
// Loading a blurred low quality image placeholder // while the original image is being loaded <IKImage path="default-image.jpg" lqip={{ active: true, quality: 20 }} width="400" />
Combining lazy loading with low-quality placeholders
You have the option to lazy-load the original image only when the user scrolls near them. Until then, only a low-quality placeholder is loaded. This saves a lot of network bandwidth if the user never scrolls further down.
// Loading a blurred low quality image placeholder // and lazy-loading original when user scrolls near them <IKImage path="default-image.jpg" transformation={[{ height:300, width:400 }]} lqip={{ active:true }} loading="lazy" height="300" width="400" />
Uploading files in React
Let's now learn how to upload an image to our media library.
React SDK provides IKUpload
component which renders an input type="file"
tag that you can use to upload files to the ImageKit media library directly from the client-side.
To implement this functionality, a backend server is needed to authenticate the request using your API private key.
Setup the backend app
For this quickstart guide, we will create a sample Node.js server which will provide an authentication endpoint at http://localhost:3001/auth
.
Let's create a file index.js
inside server
folder in the project root.
mkdir server touch server/index.js
Install the basic packages needed to create a dummy server for ImageKit backend authentication:
npm install --save express imagekit
We will use the ImageKit Node.js SDK to implement http://localhost:3001/auth
.
The backend SDK requires your API public key, private key, and URL endpoint. You can obtain them from Developer Options and URL endpoint pages respectively.
This is how server/index.js
file should look now. Replace <YOUR_IMAGEKIT_URL_ENDPOINT>
, <YOUR_IMAGEKIT_PUBLIC_KEY>
and <YOUR_IMAGEKIT_PRIVATE_KEY>
with actual values:
/* This is our backend server. Replace YOUR_IMAGEKIT_URL_ENDPOINT, YOUR_IMAGEKIT_PUBLIC_KEY, and YOUR_IMAGEKIT_PRIVATE_KEY with actual values */ const express = require('express'); const app = express(); const ImageKit = require('imagekit'); const imagekit = new ImageKit({ urlEndpoint: '<YOUR_IMAGEKIT_URL_ENDPOINT>', publicKey: '<YOUR_IMAGEKIT_PUBLIC_KEY>', privateKey: '<YOUR_IMAGEKIT_PRIVATE_KEY>' }); // allow cross-origin requests app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.get('/auth', function (req, res) { var result = imagekit.getAuthenticationParameters(); res.send(result); }); app.listen(3001, function () { console.log('Live at Port 3001'); });
Let's run the backend server.
cd server node index.js
You should see a log saying that the app is “Live on port 3001”.
If you GET http://localhost:3001/auth
, you should see a JSON response like this. Actual values will vary.
{ token: "5dd0e211-8d67-452e-9acd-954c0bd53a1f", expire: 1601047259, signature: "dcb8e72e2b6e98186ec56c62c9e62886f40eaa96" }
Configure authentication in the frontend app
Now that we have our authentication server up and running, let's configure the publicKey
and authenticator
in the frontend React app:
Add the following to src/App.js
file to initialize the SDK with auth params:
const publicKey = '<YOUR_IMAGEKIT_PUBLIC_KEY>'; const authenticator = async () => { try { const response = await fetch('http://localhost:3001/auth'); if (!response.ok) { const errorText = await response.text(); throw new Error(`Request failed with status ${response.status}: ${errorText}`); } const data = await response.json(); const { signature, expire, token } = data; return { signature, expire, token }; } catch (error) { throw new Error(`Authentication request failed: ${error.message}`); } };
Now, pass these values as props into a new IKContext
instance which will hold our upload component:
<IKContext publicKey={publicKey} urlEndpoint={urlEndpoint} authenticator={authenticator} > {/* ...child components */} </IKContext>
This is how src/App.js
should look now. Replace <YOUR_IMAGEKIT_URL_ENDPOINT>
and <YOUR_IMAGEKIT_PUBLIC_KEY>
with actual values:
import React from 'react'; import './App.css'; import { IKContext, IKImage } from 'imagekitio-react'; const urlEndpoint = '<YOUR_IMAGEKIT_URL_ENDPOINT>'; const publicKey = '<YOUR_IMAGEKIT_PUBLIC_KEY>'; const authenticator = async () => { try { const response = await fetch('http://localhost:3001/auth'); if (!response.ok) { const errorText = await response.text(); throw new Error(`Request failed with status ${response.status}: ${errorText}`); } const data = await response.json(); const { signature, expire, token } = data; return { signature, expire, token }; } catch (error) { throw new Error(`Authentication request failed: ${error.message}`); } }; function App() { return ( <div className="App"> <IKContext urlEndpoint={urlEndpoint} publicKey={publicKey} authenticator={authenticator} > {/* ...client side upload component goes here */} </IKContext> {/* ...other SDK components added previously */} </div> ); } export default App;
Upload an image
For this, we will use the IKUpload
component. Let's import it from the SDK into our App.js
file:
import { IKContext, IKImage, IKUpload } from 'imagekitio-react';
Add the IKUpload
component nested within IKContext
, as well as a couple of event handlers for upload error and success, onError
and onSuccess
respectively:
import React from 'react'; import './App.css'; import { IKContext, IKImage, IKUpload } from 'imagekitio-react'; const publicKey = '<YOUR_IMAGEKIT_PUBLIC_KEY>'; const urlEndpoint = '<YOUR_IMAGEKIT_URL_ENDPOINT>'; const authenticator = async () => { try { const response = await fetch('http://localhost:3001/auth'); if (!response.ok) { const errorText = await response.text(); throw new Error(`Request failed with status ${response.status}: ${errorText}`); } const data = await response.json(); const { signature, expire, token } = data; return { signature, expire, token }; } catch (error) { throw new Error(`Authentication request failed: ${error.message}`); } }; const onError = err => { console.log("Error", err); }; const onSuccess = res => { console.log("Success", res); }; function App() { return ( <div className="App"> <h1>ImageKit React quick start</h1> <IKContext publicKey={publicKey} urlEndpoint={urlEndpoint} authenticator={authenticator} > <p>Upload an image</p> <IKUpload fileName="test-upload.png" onError={onError} onSuccess={onSuccess} /> </IKContext> {/* ...other SDK components added previously */} </div> ); } export default App;
This is how it looks in the UI:
Direct file uploading from the browser
Let’s now upload an image by selecting a file from the file input.
When you choose a file, the file is immediately uploaded. You can pass optional onSuccess
and onError
callback functions as props like we have.
You can verify that file was successfully uploaded by checking the browser console. In case of success, it should print a success message, like this:
The response object would look similar to this (values may vary):
{ fileId: "5f7d39aa80da9a54b1d7976a", filePath: "/test-upload_0GfSgMm4p.png", fileType: "image", height: 298, name: "test-upload_0GfSgMm4p.png", size: 5748, thumbnailUrl: "https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/tr:n-media_library_thumbnail/test-upload_0GfSgMm4p.png", url: "https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/test-upload_0GfSgMm4p.png", width: 298, }
After a successful upload, you should see the newly uploaded image in the Media Library section of your ImageKit dashboard.
If you don't see the image, check if there are any errors in the browser console log. Then verify whether the API private key has been configured correctly in the server app and if the server app is running.
Fetching uploaded file
Fetch uploaded image and show in UI using IKImage
with the filePath
returned in the upload response.
<IKImage path="/test-upload_0GfSgMm4p.png" />
The app should display your uploaded image correctly!
Advanced file upload
A more detailed example of how to use the file upload component (and an explanation of each advanced feature) is presented below:
import React, { useRef } from 'react'; import './App.css'; import { IKContext, IKImage, IKUpload } from 'imagekitio-react'; const publicKey = '<YOUR_IMAGEKIT_PUBLIC_KEY>'; const urlEndpoint = '<YOUR_IMAGEKIT_URL_ENDPOINT>'; const authenticator = async () => { try { const response = await fetch('http://localhost:3001/auth'); if (!response.ok) { const errorText = await response.text(); throw new Error(`Request failed with status ${response.status}: ${errorText}`); } const data = await response.json(); const { signature, expire, token } = data; return { signature, expire, token }; } catch (error) { throw new Error(`Authentication request failed: ${error.message}`); } }; const onError = err => { console.log("Error", err); }; const onSuccess = res => { console.log("Success", res); }; const onUploadProgress = progress => { console.log("Progress", progress); }; const onUploadStart = evt => { console.log("Start", evt); }; function App() { const ikUploadRefTest = useRef(null); return ( <div className="App"> <h1>ImageKit React quick start</h1> <IKContext publicKey={publicKey} urlEndpoint={urlEndpoint} authenticator={authenticator} > <p>Upload an image with advanced options</p> <IKUpload fileName="test-upload.jpg" tags={["sample-tag1", "sample-tag2"]} customCoordinates={"10,10,10,10"} isPrivateFile={false} useUniqueFileName={true} responseFields={["tags"]} validateFile={file => file.size < 2000000} folder={"/sample-folder"} extensions={[{ "name": "remove-bg", "options": { "add_shadow": true, }, }]} webhookUrl="https://www.example.com/imagekit-webhook" // replace with your webhookUrl overwriteFile={true} overwriteAITags={true} overwriteTags={true} overwriteCustomMetadata={true} // customMetadata={{ // "brand": "Nike", // "color": "red", // }} onError={onError} onSuccess={onSuccess} onUploadProgress={onUploadProgress} onUploadStart={onUploadStart} transformation = {{ pre: 'l-text,i-Imagekit,fs-50,l-end', post: [ { 'type': 'transformation', 'value': 'w-100' } ] }} // style={{display: 'none'}} // hide the default input and use the custom upload button ref={ikUploadRefTest} /> <p>Custom Upload Button</p> {ikUploadRefTest && <button onClick={() => ikUploadRefTest.current.click()}>Upload</button>} <p>Abort upload request</p> {ikUploadRefTest && <button onClick={() => ikUploadRefTest.current.abort()}>Abort request</button>} </IKContext> {/* ...other SDK components added previously */} </div> ); } export default App;
Custom Upload Button
We have created a ref
to the input
used inside the IKUpload
component called ikUploadRefTest
. The IKUpload
component can be given styling via className
or style
(style={{display: 'none'}}
) to hide the default file selector. Then we can use the custom upload button as described above.
Abort uploads
We have created a ref
to the IKUpload
component called ikUploadRefTest
. This ref
can be used to call the abort
method in the IKUpload
component and can be used to abort the ongoing upload.
Upload start
The onUploadStart
prop is called when the file upload starts. This can be used for common use cases like showing a spinner, progress bar, etc.
Show progress bar
The onUploadProgress
prop can be passed like above, which will have a ProgressEvent. This can be used to show the percentage of upload progress to the end user.
Validate file before upload
Arbitrary validation (file type, file size, file name) etc can be added using the validateFile
prop. An example has been added above that shows how to prevent upload if the file size is bigger than 2 MB.
Additional options to the upload function
All the parameters supported by the ImageKit Upload API can be passed as shown above (e.g. extensions
, webhookUrl
, customMetadata
etc.)
Rendering videos
Rendering videos works similarly to rendering images in terms of usage of urlEndpoint
param (either directly or via IKContext
).
Loading video from relative path: Import IKVideo
from the SDK:
import { IKVideo } from 'imagekitio-react';
Now let's add it to our App. Along with the video path prop, it also needs the relevant urlEndpoint
(either directly or via IKContext
):
<IKContext urlEndpoint={<YOUR_IMAGEKIT_URL_ENDPOINT>}> <IKVideo className='ikvideo-default' path={videoPath} transformation={[{ height: 200, width: 200 }]} controls={true} /> </IKContext>
A more complex example:
<IKContext urlEndpoint={<YOUR_IMAGEKIT_URL_ENDPOINT>}> <IKVideo className='ikvideo-with-tr' path={videoPath} transformation={[{ height: 200, width: 600, b: '5_red', q: 95 }]} controls={true} /> </IKContext>
Error boundaries
We strongly recommend using Error Boundaries to handle errors in the React UI. ErrorBoundary
is used to gracefully handle errors anywhere in the child component tree of a React app.
It can be used to log errors and display a fallback UI instead of the component tree that crashed.
Example:
<ErrorBoundary> <IKImage publicKey={publicKey} urlEndpoint={urlEndpoint} path={path} transformation={[{ height: 300, width: 400 }]} /> </ErrorBoundary>