0

I was tried to add a CSS class on child component () with some delay from the parent component when it receives new props to show a DIV with some animations of the child component (). However, the delay is not working and it's just shown at once.

class Students extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            config:[],
            studentName: '',
            studentNote: '',
            isClassReady: false,
            annimClass:false
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({isClassReady : true})
        if(this.state.isClassReady){
            setTimeout(() => {
                this.setState({
                    annimClass: true
                });
            }, 500);
        }
    }

    onClickClassHandler = () => {
        // Ajax call and get data and set to config state
    }

    render() {
        return (
            <div className="container">
                <div className="student-info">
                    <h3 className="student-info--name">{this.state.studentName}</h3>
                    <p className="student-info--note">{this.state.studentNote}</p>
                </div>

                <div className="student-action">
                    <div className="student-action__class">
                        <button className="button" onClick={this.onClickClassHandler}>Select Class</button>
                    </div>
                </div>
                {
                    this.state.isClassReady &&
                    <StudentClass config={this.state.config} annimReady={this.state.annimClass}  />
                }
            </div>
        );
    }
}


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

    render() {
        return (
            <div
                className={
                    classNames('student-classes', {
                        'annim-slide-up': this.props.annimReady
                    })
                }
            >
                {
                    // content here
                }
            </div>
        );
    }
}
Daniel Smith
  • 1,626
  • 3
  • 29
  • 59
  • componentWillReceiveProps is Deprecated now , You can use static getDerivedStateFromProps(nextProps, prevState) { } instead. – Arpit Vyas Feb 25 '20 at 10:54

1 Answers1

1

setState is asynchronous, so the next line is probably running before setState is finished setting. Try using a callback to force synchronicity:

componentWillReceiveProps(nextProps) {
  this.setState({isClassReady : true}, () => {
    setTimeout(() => {
      this.setState({
        annimClass: true
      });
    }, 500);
  }
}
Sydney Y
  • 2,912
  • 3
  • 9
  • 15