David Judilla
David Judilla

Reputation: 11

How to force child components to rerender?

I'm currently initializing child components in the parent and putting them into an array. I'm passing a function into the children's props that just gets state.

 <QuestionContainer
    error={ () => this.state.currentError }
 />

The problem is that when I do this.setState({ currentError: x }) in the parent the child won't rerender because the error prop hasn't actually changed. I've tried this.forceUpdate to no avail.

I know I could design it in a way where I don't need to initialize the child components into an array, but I'm wondering how I would force a rerender in this situation.

Upvotes: 1

Views: 1813

Answers (3)

Lucas Ferronato
Lucas Ferronato

Reputation: 119

<QuestionContainer
    error={ () => this.state.currentError }
    ref="container"
 />

then

this.refs.container.forceUpdate()

dunno if this is the better approach tho

Upvotes: 2

tobiasandersen
tobiasandersen

Reputation: 8688

It's not clear why you pass a function that returns the value of currentError, instead of just the value itself. Couldn't you just pass it like this:

<QuestionContainer error={this.state.currentError} />

And then, in QuestionContainer's render, use it like e.g.

render() {
  return (
    <div>{this.props.error}</div>
  )
}

If you want your example to work you need to call the function in QuestionContainer:

render() {
  return (
    <div>{this.props.error()}</div>
  )
}

Upvotes: 1

Igorsvee
Igorsvee

Reputation: 4211

You could also have some counter variable in the parent's state and increment it every time you setState so if you pass it down to the child it should trigger the child's rerender.

Upvotes: 0

Related Questions