Search code examples
javascriptpropertiesnestedreactjschildren

Rendering children in React, losing props data


I have three react components rendering checkbox groups.

Queries -> renders a group
Query -> renders checkboxes
QueryItem -> render single input[type=checkbox]

I pass down the data coming from Queries as props for the children:

<div className="group queries">
  {component.state.groups.map((group, index) => {
    return <Query key={group.key} data={group} />
  })}
</div>

Then in Query:

<div>
  <h1>{component.props.data.label}</h1>

  <ul>
    {component.props.data.queries.map( (query, index) => {
      return <QueryItem key={query.key} data={query} />
    })}
  </ul>
</div>

And finally in the QueryItem component:

<li>
  <input type='checkbox'
    ref="input"
    defaultChecked={component.props.data.checked}
    onChange={component.checkChanged}
    name={component.props.data.id}
    id={component.props.data.id} />

  <label htmlFor={component.props.data.id}>
    {component.props.data.label} <em>({component.props.data.total})</em>
  </label>
</li>

The data gets rendered correctly. However, when the onChange (checkChanged function) gets invoked:

checkChanged (e) {
  console.log(component.props.data)
}

the data in component.props.data is the data from the last QueryItem that was rendered. So, basically, the data is always the same and does not represent the data that was rendered.

You can see, I use the key attribute to make sure the component is unique. If I inspect the data-reactid, I can see they are unique.

What is going on? What am I doing wrong in the type of setup? Goal of this setup is to invoke a data-call when a checkbox is changed and then trickling down the data from Queries to Query to QueryItem.


Solution

  • Did you by accident declare the variable 'outside the class'? This can lead to unexpected behaviour. Try to initialize all variables properly and see if the problem persists