How to make a resizable element in React JS

React JSJavascript LibraryFront End Technology

In this article, we will see how to make a resizable element in React JS. We always create resizable textarea in HTML, but when it comes to creating other elements resizable, it seems impossible. In React, we can create resizable elements easily using a simple library.

Example

First install the following package −

npm install --save re-resizable

re-resizable is used to import a resizable container which will be used to add Resizable functionality to any DOM element.

Add the following lines of code in App.js

import React, { useState } from "react";
import { Resizable } from "re-resizable";
export default function App() {
   const [state, setState] = useState({ width: 320, height: 200 });
   return (
      <Resizable
         style={{ marginLeft: 500, marginTop: 200, border: "1px solid black" }}
         size={{ width: state.width, height: state.height }}
         onResizeStop={(e, direction, ref, d) => {
            setState({
               width: state.width + d.width, height: state.height + d.height,});
            }}>
         Sample with size
      </Resizable>
   );
}

Explanation

  • Adding any element inside <Resizable> makes it resizable.

  • The size attribute defines the size of the resizable component.

  • onResizeStop defines what to do when the user tries to resize the element. Here we change width and height of the element in State which makes the required changes in the size attribute.

  • Arguments like d.width and d.height define how much the width or height should increase or decrease.

Output

On execution, it will produce the following output −

raja
Published on 28-Sep-2021 12:25:01

Advertisements