In reacting whatever we write that looks like HTML is not pure HTML actually. All the HTML looking stuff are JSX, Behind the scene, they are converted to vanilla JavaScript using babel. These all work in this way to make the developers’ life easier. Since JSX are not HTML that’s why we do have any direct reference to the HTML elements and that’s why we can’t direct fetch properties of any HTML element. To fetch the elements’ property, React gives something called as ‘ref’. Using ref we can create a direct reference to any HTML elements and get controlled over HTML elements properties. Here we use the ‘ref’ system to fetch image height and width.
Example 1: This example illustrates how to fetch the current height and width of the image.
-
index.js:
Javascript
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App />, document.querySelector( '#root' ))
|
-
App.js:
Javascript
import React, { Component } from 'react'
class App 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>GeeksforGeeks</h3>
{ }
<img ref={ this .imgRef} src=
<div>
<button onClick={ this .handleClick}>Get image details</button>
</div>
{ this .renderDetails()}
</div>
)
}
}
export default App
|
Output :

Example 2:
-
index.js:
Javascript
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App />, document.querySelector( '#root' ))
|
-
App.js:
Javascript
import React, { Component } from 'react'
class App extends Component{
constructor(props){
super (props)
this .state = {height: null , width: null , isIncrease: false }
this .handleClick = this .handleClick.bind( this )
this .imgRef = React.createRef()
}
handleClick(){
const height = this .imgRef.current.clientHeight
const width = this .imgRef.current.clientWidth
alert(`
Height : ${height}
Width : ${width}
`)
}
render(){
return (
<div>
<h3>GeeksforGeeks</h3>
{ }
<img ref={ this .imgRef} src=
<div>
<button onClick={ this .handleClick}>
Fetch dimension
</button>
</div>
</div>
)
}
}
export default App
|
Output :

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
30 Sep, 2020
Like Article
Save Article