0

What I'm trying to do is in a hook componentDidUpdate find height of a block and then set a height: 0. So I can animate height after all of this block. I have multiple blocks and content is different. Here is my hook

state = {
    height: 0,
    active: true
}

myRef = React.createRef();

componentDidMount() {
    console.log(this.myRef.current.offsetHeight, "before");
    this.setState({...this.state, height: this.myRef.current.offsetHeight})
    console.log(this.state.height, "after")
    this.setState({...this.state, active: false})
}

As you can see on a picture console.log shows before right height, then I assign this height and then second console.log still shows me 0here is a pic

I think I have issue with async code, but don't know what is exactly could be a solution By the way trying to do an accordion.

Eldar Tailov
  • 358
  • 5
  • 18
  • Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Zeno Dalla Valle Mar 29 '21 at 17:27

1 Answers1

0

setState is asynchronous functions

state = {
    height: 0,
    active: true
}

myRef = React.createRef();

componentDidMount() {
    console.log(this.myRef.current.offsetHeight, "before");
    this.setState({height: this.myRef.current.offsetHeight}, () => {console.log(this.state.height, "after")})
    this.setState({active: false})
}
Anhdevit
  • 1,926
  • 2
  • 16
  • 29