creating an identical copy of a dynamic element's size

I am currently working on a project using react js where I need to incorporate multiple images. My goal is to have standard background divs / rectangles that match the exact size of each image, allowing for animations to be performed on top of them. The snippet below shows what I have tried so far. However, I am uncertain about how to dynamically inform CSS of the correct dimensions of each image in order to replicate them. I experimented with creating an identical second image and applying some kind of overlapping solution, but it did not maintain the original image's dimensions. What would be the best approach to creating a background rectangle that always matches the size of the provided image? Thank you!

class App extends React.Component {
    constructor(props) {
    super();
    this.state = {
      onClik: false
    }
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick()  {
    this.setState({onClick: !this.state.onClcik });
  }

  render() {
    return (
      <div className="parent-div">
        <button onClick={this.handleClick}>Click Me!</button>
       <div className="child-div">
        <img className={this.state.onClick ? "on" : "off"} src="https://imgflip.com/s/meme/Cute-Cat.jpg" />
        <div className="background-div"></div>
       </div>
       <div className="child-div">
        <img className={this.state.onClick ? "on" : "off"} src="http://www.readersdigest.ca/wp-content/uploads/2011/01/4-ways-cheer-up-depressed-cat.jpg" />
      <div className="background-div"></div>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
img {
  width: 25%;
}

.on {
  transform: translateX(90px);
}

.background-div {
  background-color: red;
  height: 100px;
  width: 80px;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>

Answer №1

It's possible that the divs are the same size as the images, but I'm not entirely sure if that was what you were searching for.

Take a look at the revised code below:

class App extends React.Component {
    constructor(props) {
        super();
        this.state = {
            onClick: false
        }
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.setState({ onClick: !this.state.onClick });
    }

    render() {
        return (
            <div className="parent-div">
                <button onClick={this.handleClick}>Click Me!</button>
                <div className="child-div">
                    <img className={this.state.onClick ? "on" : "off"} src="https://imgflip.com/s/meme/Cute-Cat.jpg" />
                </div>
                <div className="child-div">
                    <img className={this.state.onClick ? "on" : "off"} src="http://www.readersdigest.ca/wp-content/uploads/2011/01/4-ways-cheer-up-depressed-cat.jpg" />
                </div>
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('app'));
img {
  width: 25%;
}


.on {
  transform: translateX(80px);
}

.child-div {
  height: 100px;
  width: 80px;
  position: relative;
}

.child-div img {
  width: 100%;
  height: 100%;
}

.child-div:after {
  content:"";
  position:absolute;
  width:100%;
  height:100%;
  left: 0;
  background: red;
  z-index: -1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>

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

How do these techniques vary within the classroom setting?

I'm fresh to diving into the realm of react and I find myself puzzled by the nuances between these two class methods doSomething=()=>{ console.log("Something") } and doSomething() { console.log("Something") } At first glance, they appear ...

Deploying my node.js project on a live server

I recently started using node.js and built a project with create-react-app, incorporating react, react-redux, and react-router. Now that I am ready to upload my project to a live server, I'm unsure whether I need to include the node_modules folder i ...

"Invalid operation" error encountered within a Flask function in Python

I am trying to store a 'person' resource in a .ttl file using a JavaScript function: Here is my SPARQL query: @app.route('/registraAnnotatore/<author>+<mail>', methods=['POST']) def registraAnnotatore(author, ...

The issue of JQuery recursion not properly focusing on a textbox

Can anyone help with a jquery focus issue I'm experiencing? My goal is to address the placeholder problem in IE by focusing on an element and then blurring it to display the placeholder. This functionality is being used in a modal form. Initially, e ...

Tips on building an immersive interactive panoramic website

I have a vision for a website that will simulate being in a room, where users can explore the space with limited panoramic views - allowing them to look up/down 30 degrees and left/right 45 degrees. In addition, I would like to integrate interactive object ...

What's the importance of including (req, res, next) in the bodyParser function within Express?

My original use of bodyParser looked like this: app.use(bodyParser.json()); However, I now have a need to conditionally use bodyParser: app.use((req, res, next) => { if (req.originalUrl === '/hooks') { next(); } else { ...

Modifying an image or audio using document.getElementByID("...").src=x+".png" is not effective

I'm having trouble figuring out why it's not working. I've searched online and here, but all I could find were tutorials that didn't include the variable or questions that were too specific. Can someone help me with this? <html> ...

Creating an Android application that integrates HTML styling efficiently

I currently have a social networking site with a mobile web version, and my goal is to package that view into an Android app and potentially enhance it with a custom splash screen. Essentially creating a branded browser window. If you have any tips or adv ...

Can you explain the purpose of the MomentInput type in ReactJS when using TypeScript?

I am currently facing an issue where I need to distinguish between a moment date input (material-ui-pickers) and a normal text input for an event in my project. const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { const i ...

Retrieve the size of the attribute of the initial array using a different array

I am working with two arrays array1 = [ {name: "samsung", views: 1200}, {name: "apple", views: 200} ] array2 = [ {name: "samsung-1234", views: 200}, {name: "apple-2332", views: 200}, {name: "samsung-6543", views: 400}, {name: "sam ...

Scrolling presentation with dynamic animations

Does anyone have any suggestions for creating a scrolling effect similar to the one on this website? I want to implement a scroll effect where each presentation page is revealed one by one when the user scrolls using their mouse wheel, encouraging them to ...

Using the ng-show directive in AngularJS allows you to pass elements in

Web Development <li ng-show="sample($event)" TestLi</li> JavaScript Functionality $scope.sample = function($event){ //$event is undefined //perform some action } I have experimented with passing the HTML element using ng-click, but I am curio ...

What is the reason for the difference in width between Bootstrap-5 row and regular div blocks?

My code may seem simple, but I have encountered an issue with it: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99fbf6f6edeaedebf8e9d9acb7abb7a9">[email protected]</a ...

maintaining the alignment of three div elements

I am struggling to keep three divs side by side within a container, each containing an image and text below it. I had this layout working perfectly before, but now the right div falls underneath the other two when the screen size is reduced, followed by th ...

Using absolute positioning for child elements within a table cell division in CSS

Similar Question: Is it possible to position items relatively or absolutely within a display: table-cell? I am working with a display: table layout example. You can view the demo here. In the second panel, there is a #pos div that has a position: abs ...

How can I set the initial screen in react-native-navigation without adding it to the tab bar?

How can I set the initial screen on my React Native app without making it a tab? I want to be able to navigate to different screens using navigator.push even when outside of a specific screen. Is there a way to achieve this? Navigation.setDefaultOptions( ...

Possible rephrased version: "Encountering a Jquery clash

It appears that the issue causing my problem may be a Jquery conflict. Please correct me if I am wrong after reviewing the information below. I am new to Jquery and attempting to add a dropdown plugin to a website. The attempt is successful, but an existi ...

Encountering an error message stating "Please enable JavaScript to run this application" when making React API calls after deploying a ReactJs app on the Firebase server

I'm currently working on a React JS app that calls various APIs. The backend of this application is a NodeJs server deployed in GCloud. While everything runs smoothly when I test the React app locally, I encountered an issue after deploying it to Fir ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Troubleshooting the inability to set percentage values in Bootstrap styling

My goal is to create a bar with thin bars, but my use of Bootstrap limits my control over sizes. <template> <div class="container-fluid mx-auto"> <div class="row"> <div class="square rounded-pill&qu ...