How to achieve automatic height adjustment within a parent container using absolute positioning

My component is defined like this:

class Test extends React.Component {
outterDivStyles() {
    return {
        position: "relative",
        width: "100%",
        overflow: "hidden",
        /*height: this.props.height || 200*/
    }
}

innerDivStyles(){
    return {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        width: "1000%",
        transition: "left .5s",
        transitionTimingFunction: "ease"
    }
}
render(){
    return(
    <div>
            <div ref="detailsOutterDiv" className="detailsOutterDiv" style={this.outterDivStyles()}>
                <div ref="detailsInnerDiv" className="detailsInnerDiv" style={this.innerDivStyles()}>
                   <div className="slide" ><img src="http://placehold.it/250x200" /></div>
                </div>
            </div>
        </div>
  )
}
React.render(<Test />, document.getElementById('container'));

The associated CSS rules are as follows:

.detailsOutterDiv{
  background-color: #f00;
  /*height: 200px;*/  //if the height is 200px, then it's ok, but can it be done without that?
  width: 300px;
  display: block;
}

.slide img{
  display: block;
  height: auto;
}

Is there a method to ensure that the image displays with full height even if the parent div doesn't have a specific height?

You can view the code snippet on jsfiddle.

Answer №1

To accurately determine the height of detailsInnerDiv, you need to wait for the image to finish loading.

To achieve this, you must utilize the offsetHeight method to capture the height, save it in the component's state, and then apply it to the detailsOutterDiv.

A possible implementation could look something like this:

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      height: 0
    };
  }  
  get outterDivStyles() {
      return {
          position: "relative",
          width: "100%",
          overflow: "hidden",
      }
  }
  get innerDivStyles(){
      return {
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          width: "1000%",
          transition: "left .5s",
          transitionTimingFunction: "ease"
      }
  }
  render(){
      return(
        <div>
              <div
                  ref="detailsOutterDiv"
                  className="detailsOutterDiv"
                  style={{...this.outterDivStyles,height : this.state.height }}
              >
                    <div 
                       ref={node => this.detailsInnerDiv = node}
                       className="detailsInnerDiv"
                       style={this.innerDivStyles}
                    >
                     <div className="slide" >
                       <img 
                         onLoad={() => this.setState({height:this.detailsInnerDiv.offsetHeight})}
                         src="http://placehold.it/250x200"
                       />
                     </div>
                  </div>
              </div>
          </div>
    )
  }
}

Check out the code on jsfiddle

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

curved edges and accentuate the chosen one

I've been working on an angularJS application that includes a webpage with multiple tabs created using angularJS. Check out this example of the working tabs: http://plnkr.co/edit/jHsdUtw6IttYQ24A7SG1?p=preview My goal is to display all the tabs with ...

After attempting to implement immutable js with Redux, my state mysteriously vanished into the ether

Starting my development journey with reactjs and redux, I thought it would be beneficial to incorporate immutable.js into my workflow while using redux. However, things took a turn for the worse. Everything seemed to crash, making me wonder if I needed mo ...

Place the navigation elements vertically in a single column

My menu bar is structured as shown below <header> <nav> <a href="#">Home</a> <a href="#">Our Story</a> <a href="#">Tools</a> <a href="#">Technolo ...

Loading data from multiple components in React Router can be streamlined by using a single loader animation to preload

I'm working on an app that requires a dynamic header which loads an external file using a fetch request. Once a user logs in, they are taken to a portal at /portal. I've defined a layout like this: export const UserLayout = ({ children }) => ...

Build a flexible Yup validation schema using JSON data

I am currently utilizing the power of Yup in conjunction with Formik within my react form setup. The fields within the form are dynamic, meaning their validations need to be dynamic as well. export const formData = [ { id: "name", label: "Full n ...

A guide to injecting HTML banner code with pure Vanilla Javascript

Looking for a solution to incorporate banner code dynamically into an existing block of HTML on a static page without altering the original code? <div class="wrapper"><img class="lazyload" src="/img/foo01.jpg"></div> <div class="wrapp ...

Converting a ref or div to an Excel format using JavaScript or jQuery

I am facing an issue with exporting multiple tables to Excel in a React project. The main problem is that when I try to export the tables using libraries like "react-html-table-to-excel-3", only the first table gets exported and not the nested table insi ...

Having two owl carousels on one page is causing some issues

Struggling to implement two owl carousels on my page. Gif: View Gif Here The first carousel (shown at the top in the gif) is functioning perfectly. However, the second one (beneath the first in the gif) is not behaving as expected. Instead of displaying ...

I am struggling to link my JS application with a PHP file as it is showing "PHP file not found

I am facing an issue with my JS application. I am unable to send data from jQuery to a PHP file, as I encountered this error message: POST https://magazyn.rob-tech.pl/savesettings.php 404 The app is running on PORT=8080 npm run start and the package.json ...

Trouble persisting with emailjs even after successful installation

After running the command npm install emailjs-com --save to install email-js in my project, I attempted to import emailjs from "emialjs-com". However, I encountered an error stating that it can't resolve 'emialjs-com' in '/Use ...

Dealing with the name attribute in an array of ngModels in Angular 4

In this scenario, I have a class that defines hobbies and a user. Here is the structure: interface IHobby { name: string; type: string; } class User { constructor(public name: string, public hobbies: IHobby[]) { } } Now, when implementing a templa ...

Coloring a table in vue.js based on performance rankings

I'm facing an issue with sorting my data performance in vue js. Here is the script I have created so far: <template> <div> <div class="row"> <h2> Campaign Performance </h2> <table class=&q ...

Using an ng-repeat directive alongside an if condition in Angular

My website contains a vast array of 30 articles, previously represented by around 300 lines of HTML code, but now condensed to just 10 lines with angularjs. However, certain articles hold special significance and require specific display criteria. Check ou ...

Utilizing Data Filters to Embed HTML in Vue.js?

I have been attempting to utilize the Filter feature in Vue.js to insert HTML tags within a String. The documentation indicates that this should be achievable, however, I am not having any success. The objective is for the data to be just a String that is ...

What could be the reason behind the disappearance of the lines in my table that was created with the help of HTML, CSS, and JavaScript?

When I added the Modal trigger, the table lines changed. I suspect it has to do with the buttons in the table. I'm new to HTML/CSS/JS so this whole experience is quite different for me. Any advice or tips for future projects would be greatly appreciat ...

Setting background images in Bootstrap

Having trouble understanding how to set Bootstrap background images. Can anyone provide guidance on the correct syntax for displaying a background image from a local file? In my page html, I have two different lines: <body class ="bg-image" style="backg ...

Data-bind knockout select knockout bind data

Hello! I am a beginner at using knockout and I have encountered an issue with data-binds and the "option" binding. My goal is to display two drop downs populated with data from my database. Surprisingly, I have managed to get the first drop down working pe ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...

Is Skrollr's performance affected when images are included?

I've recently been experimenting with the skrollr plugin to build a parallax webpage optimized for iOS. I've noticed that when I solely use text, the scrolling effect is smooth and quick. However, as soon as I add a background image using CSS or ...

Using State Variable (useState) in Event Handlers: A Guide

I am facing an issue with my React Functional Component. It receives a prop from useState() and works fine in most cases, but when used in an EventListener, it doesn't update as expected. I have tried several solutions without success. If anyone can ...