Zet Zet - 3 years ago 153
React JSX Question

cannot setState in React app

I'm trying to create an element in React that would fade in after loading page.
From debugging I understand that setState is not working as I would like it to work.

const divHeight = 100;
const divWidth = 300;

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

this.state = {
h: divHeight,
w: divWidth
};

this.fadeIn = this.fadeIn.bind(this);
}

fadeIn(){
// alert('fadeInFunc');
var divH = document.getElementById('kwadrat').clientHeight;

while(divH <= 400){
divH = divH + 5;
this.setState({ h: divH });
var sh = this.state.h;
};
}

render(){
return(
<Proba style = {{height: this.state.h}}/>
)
}

componentDidMount(){
alert('fadeInCall');
this.fadeIn();
}
}


and second part:

import React from 'react';

class Proba extends React.Component{
render(){
return(
<div ref = 'kwadrat' id = 'kwadrat'>
{alert('kwadrat')}
</div>
)
}
}


why I cannot update the state and change the size of the div?

Answer Source

You have three problems in your code :

  1. The while loop is too fast for you to see any motion. To fix this, I proposed a setInterval solution below.
  2. You are giving style to the <Proba> component thinking it's the default HTML attribute. It's in fact nothing but a prop, the solution below fixes that as well.
  3. You are placing spaces around the = signs in the defintion of your props and that is not recommended.

Here is the render method of the Proba component :

function render() {
    return (
        // set the style as a normal prop, it will work here because this
        // is a simple <div>, not a component
        <div ref="kwadrat" id="kwadrat" style={ this.props.style }>
            kwadrat
        </div>
    );
}

Here is the fadeIn method :

fadeIn() {
    const interval = setInterval(() => {
        this.setState({ h: (this.state.h + 5) });
        if (this.state.h >= 400) {
            clearInterval(interval);
        } 
    }, 50);
}

I have added a codepen that shows a working example, in which I have added two different configurations for the movement of the <div> (step and time).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download