REACT JS

How to resize images in React JS

How to resize images in React JS

Resizing images in a React JS application is a common requirement, especially when dealing with user uploads or dynamically loaded images. Properly resizing images ensures optimal performance and a better user experience. In this blog post, we will explore various methods to resize images in React JS, including using CSS, a JavaScript library, and an HTML canvas element.

Prerequisites

Before we start, make sure you have the following:

  1. A basic understanding of React JS.
  2. Node.js and npm installed on your machine.
  3. A React project set up. If you don’t have one, you can create it using Create React App:
   npx create-react-app resize-image-demo
   cd resize-image-demo
   npm start

Methods to Resize Images

Method 1: Using CSS

One of the simplest ways to resize images in React is by using CSS. You can set the width and height properties directly in your CSS or inline styles.

Example:

import React from 'react';

function App() {
  return (
    <div className="App">
      <h1>Resize Image Using CSS</h1>
      <img
        src="https://via.placeholder.com/600"
        alt="Example"
        style={{ width: '300px', height: 'auto' }}
      />
    </div>
  );
}

export default App;

In this example, the image is resized to a width of 300px while maintaining its aspect ratio.

Method 2: Using a JavaScript Library (React Image File Resizer)

For more control over image resizing, you can use a JavaScript library like react-image-file-resizer. This library provides an easy way to resize images before uploading them or displaying them in your application.

First, install the library:

npm install react-image-file-resizer

Then, use it in your component:

import React, { useState } from 'react';
import Resizer from 'react-image-file-resizer';

function App() {
  const [resizedImage, setResizedImage] = useState(null);

  const resizeFile = (file) =>
    new Promise((resolve) => {
      Resizer.imageFileResizer(
        file,
        300,
        300,
        'JPEG',
        100,
        0,
        (uri) => {
          resolve(uri);
        },
        'base64'
      );
    });

  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    const image = await resizeFile(file);
    setResizedImage(image);
  };

  return (
    <div className="App">
      <h1>Resize Image Using React Image File Resizer</h1>
      <input type="file" onChange={handleFileChange} />
      {resizedImage && <img src={resizedImage} alt="Resized" />}
    </div>
  );
}

export default App;

In this example, the selected image is resized to 300×300 pixels before being displayed.

Method 3: Using HTML Canvas

Another approach to resizing images is by using an HTML canvas element. This method provides fine-grained control over the image resizing process.

Example:

import React, { useRef, useState } from 'react';

function App() {
  const [resizedImage, setResizedImage] = useState(null);
  const canvasRef = useRef(null);

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = (e) => {
      const img = new Image();
      img.src = e.target.result;
      img.onload = () => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        canvas.width = 300;
        canvas.height = (img.height / img.width) * 300;
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        setResizedImage(canvas.toDataURL());
      };
    };

    reader.readAsDataURL(file);
  };

  return (
    <div className="App">
      <h1>Resize Image Using HTML Canvas</h1>
      <input type="file" onChange={handleFileChange} />
      <canvas ref={canvasRef} style={{ display: 'none' }}></canvas>
      {resizedImage && <img src={resizedImage} alt="Resized" />}
    </div>
  );
}

export default App;

In this example, the image is resized using an HTML canvas element, and the resized image is then displayed.

Conclusion

Resizing images in a React JS application can be achieved using various methods, each with its own advantages. CSS provides a simple and quick way to resize images, while JavaScript libraries like react-image-file-resizer and HTML canvas elements offer more control and flexibility.

By choosing the right method for your specific use case, you can ensure optimal performance and a better user experience in your React applications. Happy coding!

You may also like

REACT JS

How to do a for loop in React JS

React.js is a popular JavaScript library for building user interfaces, and it's known for its component-based architecture. While React encourages
How to redirect to another page after login in React JS
REACT JS

How to fetch data from local JSON file in React JS

Fetching data is a fundamental part of building dynamic web applications. Often, you might need to load data from a
en_USEnglish