Thursday, July 4, 2024
HomeLanguagesReactHow to determine the size of a component in ReactJS ?

How to determine the size of a component in ReactJS ?

The size of a component is determined by the height and width of the container. It can be determined if we assign a ref to that component. The useRef function with ref attribute are used to get the current size of the component. 

The useRef hook with ref attribute is here working to create a reference to the component whose size we want to determine.

  • useRef: The useRef is a hook that allows to directly create a reference to the DOM element in the functional component.
  • Refs: Refs are a function provided by React to access DOM element and React element that you might have created on your own.

The useRef returns a ref object. This object has a property called .current. The value is persisted in the refContainer.current property. Then with the help of refContainer.current we will be able to get the height and width of that component. 

To get the height and width of component we use:

  • width: refContainer.current.offsetWidth
  • height: refContainer.current.offsetHeight

Creating React Application

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

npx create-react-app example

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

cd example

Step 3: Create folder components inside src folder of react project directory and inside the components folder create files List.jsx

Project structure: It will look like this.

Example: Basic example of how to determine the size of a component. Write down the following code in index.js, App.js and List.jsx file. 

index.js

Javascript




import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
 
ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById('root')
);
 
// If you want to start measuring performance
// in your app, pass a function to log results
// (for example: reportWebVitals(console.log))
reportWebVitals();


Filename: App.js

Javascript




import React from "react";
import List from "./components/List";
 
function App() {
    return (
        <div className="App">
            <h1>Size of Component</h1>
            <List />
        </div>
    );
}
 
export default App;


List.jsx

Javascript




import React, { useState, useEffect, useRef } from 'react';
 
function List() {
    const refContainer = useRef();
    const [dimensions, setDimensions] =
        useState({ width: 0, height: 0 });
    useEffect(() => {
        if (refContainer.current) {
            setDimensions({
                width: refContainer.current.offsetWidth,
                height: refContainer.current.offsetHeight,
            });
        }
    }, []);
    return (
        <div
            style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                height: '100%',
                backgroundColor: '#fafafa',
                margin: '20px',
            }}
            ref={refContainer}>
            <pre>
                Container:
                <br />
                width: {dimensions.width}
                <br />
                height: {dimensions.height}
            </pre>
        </div>
    );
}
 
export default List;


Step to run the application: Run the application using the following command:

npm start

Output: 

size of component

With the help of the ref object, we are able to determine the width and height of the container which actually is the size of the component.

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!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments