How to change color of rectangle on resizing using React.js ?
Last Updated :
23 Nov, 2023
In web development, interactive UI elements can definitely enhances the user experience. One common task is altering an element’s appearance based on user actions, such as resizing a window.
Prerequisites:
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.
Steps to implement the above approach:
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
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...