Using React to dynamically set the width of a div element to match the width of an image

I am trying to ensure that my div is always the same width as the image it contains, even when the window is resized and the image adjusts automatically. I attempted to solve this using the useState hook, but it does not seem to respond to resize events.

    const imageElement = useRef();
    const textElement = useRef();
    const [imageWidth, setImageWidth] = useState();

    useEffect(() => {
        setImageWidth(
            imageElement.current.getBoundingClientRect().width
        );
    });

      <img
        src={profilePic}
        alt="Profile Pic"
        className="About-basic-info-image"
        ref={imageElement}
      />
      <p
        className="About-basic-info-text"
        ref={textElement}
        style={{ width: imageWidth }}
      >
        {textContent}
      </p>

Answer №1

Utilizing the useEffect in this manner will trigger only once upon the component mounting. To continuously update, you must incorporate an event listener for the resize event and then invoke setBasicInfoImageWidth

useEffect(() => {
    window.addEventListener('resize', () => setBasicInfoImageWidth(
        basicInfoImage.current.getBoundingClientRect().width
    ));
});

Alternatively, resolving this issue with CSS may be a simpler approach. For a more detailed solution, please provide a working example or a jsfiddle link for assistance with the CSS implementation

Answer №2

Using CSS alone, you have the ability to accomplish this task without relying on react State

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubles with HTML and div elements

I have a specific need to dynamically load HTML into a div container with the style attribute overflow set to hidden. I have implemented next and previous buttons for navigation, but I am facing an issue where the content overlaps at the beginning and end ...

placing a dropdown menu below the search bar

Let's say I have a container with an input search field. My goal is to position a select dropdown right below the search input, ensuring that the dropdown has the same width as the search input (similar to autocomplete functionality). Here's what ...

Knex is requesting the installation of sqlite3, but I am actually utilizing a MySQL database

While attempting to execute a query on my local MySQL database using knex, I encountered an issue where it prompted me to install the SQLite3 driver, even though my database is MySQL. To troubleshoot, I installed the SQLite3 driver to see if it would reso ...

When attempting to retrieve a data object using a Vuex action, I encounter an "Uncaught (in promise) TypeError" when trying to access the data within the object

Recently, I've been diving into Vuex and its actions for fetching data. While everything seems to be working smoothly - accessing the films object, selecting films from it - I encounter an error when trying to access specific data within a film. Vuex ...

Attempting to utilize a Jquery Ajax post method to retrieve information from my specified URL and display it within my HTML Div element

Seeking assistance in fetching real-time data using a jQuery Ajax Post method. My experience lies mainly in SQL and C#, so coding in this language is relatively new to me. I was advised to use this script, which seemed straightforward. However, despite my ...

The `d-flex flex-column` is causing the image within the div to be hidden

The setup looks like this: <div className="d-flex flex-column"> <div> Text </div> <div style={{ backgroundImage: 'url(...)' }}> </div> </div> The URL is functioning correctly. The div element is ...

Retrieve the value from a classic ASP page using an if statement and pass it to

Currently, I am attempting to assign a JavaScript value through ASP. foo('RequestMode', '<%=Request.Querystring("Mode")%>') My goal is to achieve something along the lines of: foo('RequestMode', '<%=if (Reques ...

React App Development Halted at "successfully integrated 1416 new packages in just 2 minutes"

Screenshot of my terminal Hi there! I've run into some issues while trying to set up a React app on my computer. After the npx create-react-app my-app command failed, I attempted different commands. Eventually, I tried npx create-react-app@latest-ver ...

Adjust the checkbox dimensions within the cells of a bootstrap table

I am utilizing bootstrap-table along with a column containing checkboxes. I need to adjust the size of the checkboxes in my code to be 25x25 pixels. However, when I try using the height and width CSS attributes, it does not seem to take effect. html < ...

I encountered some difficulties while attempting to install axios using npm

Recently updated and audited a total of 1446 packages in just 7 seconds Currently, 194 packages are in need of funding. Simply execute npm fund for more information There are 6 high severity vulnerabilities that need immediate attention To resolve all e ...

Guide to changing the background color of material ui drawer component using styled-components

Issue with Styling Material Ui Drawer Using Styled Components In my application, I am utilizing a Material ui drawer in conjunction with Styled components. Although I have successfully styled several simple Material ui components using Styled components a ...

Backend undergoing fluctuations in hourly values

When passing JS dateTime to the backend using ajax(axios), I encountered a discrepancy in the timestamps. Prior to the post request, I have the following timestamp: Sun Nov 04 2018 21:53:38 GMT+0500 However, upon reaching the backend, the timestam ...

Rotate images with animation using Javascript

Seeking assistance with a swinging motion using two simple functions in Javascript. As a newcomer to the language, I am looking for guidance to achieve my goal. First function: function up() { imgObj.style.left = parseInt(imgObj.style.transform = 'r ...

Tips for setting up electron.js on a linux operating system

Seeking guidance to successfully install electron.js on a Linux operating system. Here are the issues I'm encountering: Installation Command sudo npm i electron Terminal Output /usr/bin/electron -> /usr/lib/node_modules/electron/cli.js <a ...

Encounter Issue: "Describe" function not recognized. This error occurred during the activation of Mocha Test

https://i.sstatic.net/WBSm6.png Upon my installation of mocha, I encountered an issue while running a test using a command, resulting in the error message "describe is not a function." ...

Retrieving Values from Array with AngularJS Keys - A How-To Guide

I need to access a specific value from a key inside an array, like this: $scope.result = [ { "key":"logo_big", "value":"/assets/images/aaa.jpg" }, { "key":"logo_small", "value":"/assets/images/logo94x57Bis.png" }, { ...

What is the method for ensuring that the state and component have identical values?

Currently, I am diving into the world of UI design using the React library. However, I seem to be encountering some issues with my code. handleIncrement = () => { this.setState({ ...this.state, quantity: this.state.quantity + 1 }) ...

What is the best way to change routes within my React application?

I am currently facing a challenge with the Routes in my work's web application. The existing method of accessing routes involves manually typing in the extended path in the browser, which is not ideal. I want to enhance this by adding new routes that ...

What is the best way to display or conceal an array object using a toggle switch?

I'm trying to implement a show/hide functionality for descriptions when toggling the switch. Additionally, I want the switch to be initially checked and only show the description of each respective result. However, my current code is displaying all de ...

Integrating VueJs into a pre-existing .net core 5 project

I am currently working on a .net core solution that consists of 9 different projects including api, dto, data, service, etc. I now have the requirement to incorporate a project that utilizes the Vue.js framework for the frontend within this existing .net ...