If you are new to React Native app development, you can learn about setting up the development environment and creating a new project here https://reactnative.dev/docs/environment-setup.
Setting up React Native app
For this tutorial, it is recommended to use the sample React Native app as shown below. If you already have an existing React Native app, it is also possible to use that, although you would need to modify the terminal commands and configurations in this tutorial as applicable.
Let's use the react-native-cli package to build a new project:
npxreact-native@latestinitimagekitReactNative
Navigate to the project directory:
cdimagekitReactNative/
Start the metro server.
npxreact-nativestart
And now to run the app in the iOS simulator (you should have Xcode installed)
npmrunios
Or to run the app in the android simulator (you should have android studio installed)
npmrunandroid
You should see the following screen. This means the sample app has been set up correctly.
Let's configure the components required for the application.
Execute the provided command to install the packages required for the application.
Create index.js and styles.js files within the app/screens/Main directory. These files will render & style buttons facilitating navigation to different screens, which will be developed in the subsequent sections. This configuration serves as our home screen.
Create the AppComponent.js file within the app directory which will contain the screens. Add the home screen. Open the App.tsx file and add the provided code to render the AppComponent.
imagekit-javascript SDK uses URL API to parse the URL internally. In React 16 and above, this API was removed, so if you are using React 16 or above, you will have to implement a small patch with these steps.
Install the package with npm install react-native-url-polyfill
Import the package in your app's entry point i.e. App.js like this import 'react-native-url-polyfill/auto'
Initializing the SDK
Create app/lib/imagekit.js file, this is where we will initialize our SDK and create helper functions that will be used in the app.
publicKey and authenticationEndpoint parameters are optional and only needed if you want to use the SDK for client-side file upload. You can get these parameters from the developer section in your ImageKit dashboard - https://imagekit.io/dashboard/developer/api-keys.
Also initialize the SDK with parameters set in the config file app/config/imagekit.js
app/config/imagekit.js
module.exports.urlEndpoint =''; //insert your own url end point heremodule.exports.publicKey =''; //insert your own public key heremodule.exports.authenticationEndpoint =''; //your auth api path
Image URL can be created from an image path or using the absolute image URL. You can learn more about it in docs.
To create a URL from the image source (full image URL), we can create a function like this, which takes the image source and a transformation array and returns the transformed image URL.
The transformation position (path or query) is only valid when creating a URL from the image path. Transformations are always added as query parameters if the URL is created from an absolute image path using src.
Now, let's create app/screens/Fetch/index.js to fetch an image. Also, update app/AppComponent.js to include the fetch image screen.
It will look as shown below. In the sample app, the buttons are present to demonstrate the use of different transformations. You can see the full list of supported transformations here.
ImageKit JavaScript 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 Javascript SDK on Github.
You can also use h and w parameter instead of height and width.
See the complete list of transformations supported in ImageKit here.
Basic Image Resizing
Let's resize the image to a height of 150 and a width of 150.
Note: You'll need to specify height and width in the Image component of react-native accordingly as we are fetching the image from a remote url.
Let’s now see how crop mode work. We will try the pad_resize crop strategy.
In this strategy, the output image's dimension (height and width) is the same as requested, no cropping occurs, and the aspect ratio is preserved. This is accomplished by adding padding around the output image to get it to match the exact dimension as requested. You can read more about this here.
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 Overlay
Text overlay can be used to place text on an image. Here's how:
Let's learn how to upload an image to our media library.
For this, we would need a dummy backend app to authenticate our upload request. API authentication for upload always happens on the backend for security reasons.
In the following section, we will create a backend server that we can use.
Setting up the backend app
For this quickstart guide, we will create a sample Node.js server which will provide an authentication endpoint at http://localhost:8080/auth.
Let's create a file index.js inside server folder in the project root.
mkdirservertouchserver/index.js
Install the basic packages needed to create a dummy server for ImageKit backend authentication:
Head over to app/config/imagekit.js and replace the authenticationEndpoint with http://localhost:8080/auth
Upload an image
Try using react-native v0.73.0 which is the latest version at the time of writing this article, as some of the previous versions have a known issue in uploading files. If you are using a previous version and can't upgrade, you'll have to implement a workaround.
For this, let's create couple of functions in app/lib/imagekit.js file and update app/AppComponent.js to include the upload screen.
app/lib/imagekit.js
constauthenticator=async () => {try { // You can pass headers as well and later validate the request source in the backend, or you can use headers for any other use case.
constresponse=awaitfetch(authenticationEndpoint);if (!response.ok) {consterrorText=awaitresponse.text();thrownewError(`Request failed with status ${response.status}: ${errorText}`, ); }constdata=awaitresponse.json();const {signature,expire,token} = data;return {signature, expire, token}; } catch (error) {thrownewError(`Authentication request failed: ${error.message}`); }};module.exports.uploadFile=asyncfunction (file) {constres=awaitauthenticator();returnnewPromise((resolve, reject) => {imagekit.upload( { file, fileName:file.name,//you can change this and generate your own name if required tags: ['sample-tag-1','sample-tag-2'],//change this or remove it if you want...res, },function (err, result) {if (err) reject(err);resolve(result); }, ); });};
Let’s upload an image by selecting a file using the file input.
The uploader uploads whenever file input changes. You can verify that file was successfully uploaded by checking the browser console. It should print the file URL.
After a successful upload, you should see the newly uploaded file in the Media Library of your ImageKit dashboard.
If you don't see the file, check if there are any errors in the log. Make sure that the private API key has been configured. The server app is running. And the uploaded file type is supported by ImageKit.
Rendering videos
Rendering videos works similarly to rendering images.
We're going to use the react-native-video package to play video files, but you can use any other video player.
npminstallreact-native-video
Update the app/screens/Videos/index.js and app/AppComponent.js file to fetch video.