Wednesday, January 8, 2025
Google search engine
HomeLanguagesHow to change color of rectangle on resizing using React.js ?

How to change color of rectangle on resizing using React.js ?

In this article, let’s see how we can change the color of a rectangle on resizing using ReactJS.

Approach: To change the color on resizing, we need to implement two features. First, we should be able to resize the rectangle. Second, we need to detect the size of the rectangle to update the color. Therefore, for resizing, we will use a re-resizable component for React and analyze the size by using the react-resize-detector library for React.

Below is the step-by-step implementation of the above approach:

Modules Required:

  • npm
  • create-react-application

Creating React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app demo

Step 2: After creating your project folder i.e. demo, move to it using the following command:

cd demo

Step 3: Install react-resize-detector and re-resizable from npm.

npm i react-resize-detector re-resizable

Open the src folder and delete the following files:

  • logo.svg
  • setupTests.js
  • App.test.js 
  • index.css
  • reportWebVitals.js
  • App.css

Project Structure: The project should look like this:

 

Example: In this example, we’ll see how to change the color of the rectangle on resizing in ReactJS

index.js




import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
  
const root = ReactDOM.createRoot(
    document.getElementById('root')
);
  
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);


App.js




import React, { useState, useEffect } from 'react';
import { Resizable } from 're-resizable';
import { withResizeDetector } from 'react-resize-detector';
import React, { useState, useEffect } from 'react';
import { Resizable } from 're-resizable';
import { withResizeDetector } from 'react-resize-detector';
  
const App = ({ width, height }) => {
    const [color, setColor] = useState('red');
    const [state, setState] = useState({
        width: 300, height: 100
    });
  
    useEffect(() => {
        setColor(width > 200 ? width > 300 ?
            '#dacbf7' : '#f1ccf8' : '#d3f8cc');
    }, [width]);
  
    return (
        <>
            <Resizable
                style={{
                    backgroundColor: color,
                    margin: '20px',
                    border: "1px solid black",
                    color: 'green',
                    fontSize: '20px',
                    textAlign: 'center',
                    fontWeight: 'bold'
                }}
                size={{
                    width: state.width,
                    height: state.height
                }}
                onResizeStop={(d) => {
                    setState({
                        width: state.width + d.width,
                        height: state.height + d.height,
                    });
                }}>
                {`${width}x${height}`}
            </Resizable>
            <p style={{
                color: 'blue', margin: '20px',
                fontSize: '20px'
            }}>Current Color: {color}</p>
  
        </>
    );
};
  
export default withResizeDetector(App);


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments