F
F
fierfoxik2017-06-27 15:38:24
JavaScript
fierfoxik, 2017-06-27 15:38:24

How to check the dimensions of an image before it is rendered in the dom?

It is necessary to get the url of the image from the redux storage and draw it in the dom tree if it passes in height and width.
I almost managed to make a functional that is close in meaning, but only the check occurs only after the picture is drawn in the dom, and then if it does not pass the condition, I delete it.
How can I check the dimensions of an image before it is rendered in the dom?

drawImg(){
        const {imagePreviewUrl, file} = this.state;
        if (imagePreviewUrl) {
           return <div key="162" className="imgPreview">
               <img  src={imagePreviewUrl} onLoad={this.CheckImg} />
           </div>
        }
    }

    CheckImg(e){
        if(e.target.width==140 || e.target.height==205){
            alert('Обложка успешно загружена')
            e.target.parentNode.classList.add('is--checked')
        }else{
            e.target.parentNode.classList.remove('is--checked')
            e.target.src = '';
            alert('Обложка должна быть 140х205');
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2017-06-27
@fierfoxik

After the component is added to the DOM, we take src from props and create a new img DOM element, set the onLoad handler and load the image. Then we check the dimensions and set the state

class Cover extends Component { 
   state = {
     loaded: false,
     width: 0,
     height: 0,
   }

   componentDidMount() {
     const img = document.createElement('img')

     img.onload = e => {
       console.log('image loaded', img.width, img.height)
       this.setState({ loaded: true, width: img.width, height: img.height })
     }

     img.src = this.props.src
   }

  renderLoading() {
    return <div>loading... </div>
  }
  
  renderLoaded() {
    const { width, height } = this.state
    const isFits = width === 140 && height === 205
    return isFits
      ? <div>обложка успешно установлена</div>
      : <div>Обложка должна быть 140х205</div>
  }

   render() {
       return this.state.loaded ? this.renderLoaded() : this.renderLoading()
   }
}

D
davidnum95, 2017-06-27
@davidnum95

Actually, something like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question