How To Get The Height And Width Of An Image Using ReactJS

We’ll learn how to use ReactJS to obtain the height and width of an image in this tutorial.

In responding, whatever we write that appears to be HTML isn’t truly HTML.

All of the HTML-like elements are JSX, which is translated to vanilla JavaScript behind the scenes using babel.

All of these things work together to make the developers’ lives easier. We don’t have any direct references to HTML elements because JSX isn’t HTML, and we can’t directly fetch properties of any HTML element. React provides a function called ‘ref’ to get the properties of the elements.

You can see the example below.

import React, { Component } from 'react'

class Index extends Component {
    constructor(props) {
        super(props)
        this.state = { show: false }
        this.handleClick = this.handleClick.bind(this)
        this.imgRef = React.createRef()
    }

    renderDetails() {
        return this.state.show ?
            <div>
                <p><strong>Height : </strong>
                    {this.imgRef.current.clientHeight}px</p>
                <p><strong>Width : </strong>
                    {this.imgRef.current.clientWidth}px</p>
            </div> : null
    }

    handleClick() {
        this.setState({
            show: true
        })
    }

    render() {
        return (
            <div>
                <h3>How to get image width and height in ReactJS</h3>
                <img ref={this.imgRef} src=
                    'https://media.istockphoto.com/photos/colored-powder-explosion-on-black-background-picture-id1057506940?k=20&m=1057506940&s=612x612&w=0&h=3j5EA6YFVg3q-laNqTGtLxfCKVR3_o6gcVZZseNaWGk=' alt='gfg' />
                <div>
                    <button onClick={this.handleClick}>Get image details</button>
                </div>
                {this.renderDetails()}
            </div>
        )
    }
}
export default Index

You can see the output below.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories