Struggle with placement of elements using React and Flexbox

Struggling with an intriguing challenge related to the layout of components in a web application.

Let's take a look at the code snippet MyCompo.js:

import React from "react";
import tblClp from './images/WoodSquare.jpg';
import dwnArwClp from './images/DownArrow.png';
import upArwClp from './images/UpArrow.png';
import './MyCompo.css';

class MyCompo extends React.Component {
  render() {
    const elements = [...Array(3).keys()]
    const items = []
    
    for (const [index, value] of elements.entries()) {
      items.push(<SquareUnit index={index}/>)
    }
    
    return (
      <div>
        {items}
      </div>
    )
  }
}

class SquareUnit extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <React.Fragment>
        <div id={this.props.index}>
                    <div><img src={tblClp} width='130' height='109'/>
            <div className="overlay down">
                <img src={dwnArwClp} width='40' height='40'/>
                </div>
            <div className="overlay up">
                <img src={upArwClp} width='40' height='40'/>
              </div>
                    </div>
        </div>
      </React.Fragment>
    )
  }
}

export default MyCompo;

Now let's take a glimpse at the style sheet MyCompo.css:

body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.overlay {
    position: relative;
    height: 100%;
    width: 100%;
    opacity: 0.3;
    transition: .3s ease;
    background-color: transparent;
    bottom: 0;
    right: 0;
}

.down {
    top: -24%;
    left: 3%;
}

.up {
    top: -76%;
    left: 65%;
}

.container {
    position: relative;
    width: 100%;
    max-width: 400px;
}

While developing, I use this command in the terminal:

$ npm start

After fine-tuning the .down {...} and .up {...} sections within MyCompo.css and saving the file, this is what appears in the browser:

https://i.sstatic.net/CTHMs.png

The visual representation consists of three wooden square blocks, each adorned with overlayed up and down arrows.

In the above screenshot, the displayed image matches my expectations perfectly.

However, upon refreshing the browser window, the display transforms into something unexpected:

https://i.sstatic.net/vSC7s.png

This deviation from the expected output begs the question: What might be amiss in either my code MyCompo.js or MyCompo.css causing this discrepancy?

Answer №1

Upon further inspection, it appears that the .container class is missing from the parent div, resulting in the absence of the display: relative property. As a result, the arrows are being pushed outside of the container. To resolve this issue, consider adding the following code snippet:

<React.Fragment>
    <div id={this.props.index}>
        <div className="container">
            <img src={tblClp} width='130' height='109'/>
            <div className="overlay down">
                <img src={dwnArwClp} width='40' height='40'/>
            </div>
            <div className="overlay up">
                <img src={upArwClp} width='40' height='40'/>
            </div>
        </div>
    </div>
</React.Fragment>

Answer №2

The issue has been successfully resolved, and I'll outline the steps taken to resolve it.

Firstly, here is the updated source code for MyCompo.js:

    import React from "react";
    import dwnArwClp from './images/DownArrow.png';
    import upArwClp from './images/UpArrow.png';
    import './MyCompo.css';

    class MyCompo extends React.Component {
      render() {
        const elements = [...Array(3).keys()]
        
        const items = []
        
        for (const [index, value] of elements.entries()) {
          items.push(<SquareUnit index={index}/>)
        }
        
        return (
          <div>
            {items}
          </div>
        )
      }
    }

    class SquareUnit extends React.Component {
      constructor(props) {
        super(props);
      }
    
      render() {
        return (
          <React.Fragment>
            <div id={this.props.index} className='tblBlk'>
                        <div className='tblCell'>
                <div className="overlay down">
                    <img src={dwnArwClp} width='40' height='40'/>
                  </div>
                <div className="overlay up">
                    <img src={upArwClp} width='40' height='40'/>
                  </div>
                        </div>
            </div>
          </React.Fragment>
        )
      }
    }

    export default MyCompo;

Additionally, here is the revised style sheet for MyCompo.css:

    body {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
    
    .sqBlk {
        padding-top: 11px;
        padding-bottom: 11px;
    }
    
    .sqCell {
        background-image: url("./images/WoodSquare.jpg");
        width: 130px;
        height: 109px;
    }
    
    .overlay {
        position: relative;
        height: 100%;
        width: 100%;
        opacity: 0.4;
        transition: .3s ease;
        background-color: transparent;
        bottom: 0;
        right: 0;
    }
    
    .down {
        top: 60%;
        left: 4%;
    }
    
    .up {
        top: -96%;
        left: 65%;
    }

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

Significant gap in the white space between the initial and subsequent columns of the Bootstrap table

How do I eliminate the excessive white space between the Name column and the first date column that displays 24? It seems to be triggered by the Bootstrap CSS, but the reason is not clear. The issue disappears from my model when there are more dates in t ...

Error: script 'start' is not defined on Heroku

Hello there! I'm currently working on deploying an application to Heroku from my GitHub repository. To ensure that everything runs smoothly, I made some modifications to the start script in the package.json file. Specifically, I adjusted it to point t ...

Mobile Navigation Menu Appears and Disappears When Media Query Shrinks

Whenever I shrink the page, the menu quickly pops up and then slides back down. I would prefer it not to show up at all when the page shrinks. I can't figure out why this issue is occurring. I suspect that the problem lies with transitions on #nav ra ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

tips for sending the database value to the next page with ajax

Struggling to send the database value retrieved through ajax to the next page. Tried several methods but none seem to work. Could anyone provide guidance on how to achieve this? php Successfully connected to the database $sql = "SELECT * FROM `billin ...

The formatting of the `new Date()` function differs between the frontend and backend environments

Recently, I implemented a feature in my web application where users can purchase a 'One day access' pass. Upon purchase, I update the user's data with an endDate property. When the user logs in, I validate if the endDate value has expired. H ...

Display a webpage containing error messages and user input that can be sent back to the AJAX request

My form collects user information such as name, surname, etc. Here is an example of one input field: <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" value= ...

Error in Jquery click function not being triggered

I'm in the process of developing an eCommerce platform where users can choose options and have their shopping carts automatically updated using jQuery. Users will be presented with a few radio buttons to select from, and as they make their choice, th ...

A guide on implementing an id field into an object using JavaScript

Is it possible to assign a distinct identifier to every element in the JSON array with JavaScript? [ { name: 'Yosi'}, { name: 'Ben' }, { name: 'Dan' }, { name: 'Erez'} ] Desired outcome: [ {id: 1, name: 'y ...

Bring JavaScript Function into Vue's index.html File

Recently in my code files, I noticed the following: function example() { console.log("testing"); } In another file, I have something like this: <head> <script src="../src/example.js" type="text/babel"></sc ...

Using a video as a background in HTML

My code has an issue where I have set overflow: hidden in the CSS but the video is still not displaying below the text as intended. The relevant CSS snippets are: fullscreen-bg { top: 0; right: 0; bottom: 0; left: 0; overflow:hidden ...

Creating a dynamic dropdown menu using JQuery that does not automatically submit the form when a value is

Upon selecting a background color from the dropdown menu, I am generating a dynamic dropdown for text colors. The Text Color dropdown is populated correctly based on the selection of Background Color. Although the functionality works as intended, I encoun ...

Encountering a bug in the comment feature of the next.js npm module

I encountered an issue that is giving the following error messages: 10:03:56.049 ./components/navbar.js 10:03:56.049 13:33 Warning: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images. jsx-a11y/ ...

What is the correct way to utilize drei's useGLTF function?

Despite following the react-three docs and various examples, I am struggling to get drei useGLTF to function properly in my project. I have a basic Next|React|react-three/fiber project that I built from scratch. My goal is to load the astronaut example an ...

Understanding how event listeners work in documentation

I have a question about the following code snippet: on.("click", () => {...}) I am currently exploring Electron and came across a code example that uses a typical event listener function. The developer in the fat-arrow function included different ...

Unveiling Fresh URLs within an iFrame

Here is the current situation: www.mywebsite.com/Pagex.html - On this page, there is an iFrame with a default URL (src) from a different domain than the host page (Pagex.html). The code inside the iFrame is a user input form with a submit button. Upon su ...

The placeholder text feature for Google custom search is ineffective when using the Edge browser

After adding the following code to the end of the Google custom search script, I encountered an issue: window.onload = function(){ document.getElementById('gsc-i-id1').placeholder = 'Search'; }; Although this code successfully added ...

What is the process for importing a TypeScript file as a library?

My customized personal "library," dubbed methlib and saved as a .ts file on my computer, contains a plethora of classes, interfaces, functions, and more that I frequently use and prefer to keep in one convenient location. The dilemma I face now is how to u ...

Obtain the HTML content when a user clicks on an image within a

I have implemented a plugin that allows me to scroll and zoom in on an image. My goal is to click on the following image to extract the values for left and top as specified below. <img id="zoom_mw" src="<?php echo $small_image; ?>" data-zoom-ima ...

By utilizing .focus() in iOS8, the virtual keyboard will be displayed and the page will automatically scroll upon touch

In the era before iOS8, when utilizing the Javascript .focus() method on an input element, it seemed as though nothing happened - the virtual keyboard did not make an appearance. However, with the latest iOS 8 update, executing the .focus() method initiall ...