Skip to content Skip to sidebar Skip to footer

Return Checked Value From Child To Parent And To Grandparent Component Using React

I am making a list of names of students and their ID's. The Parent class calls upon Child class whenever a list element is to be rendered. export default class Parent extends Compo

Solution 1:

You can send a callback function to Child which notifies whenever it has been checked or unchecked.

const Child = ({ id, name, onChange }) => 
  <li>
    <input
      type="checkbox"
      onChange={(event) => onChange(id, event.target.checked) }
    />
    {name}
  </li>

class Parent extends React.Component {
  constructor() {
    super()

    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(id, checked) {
    console.log(`student ${id} is ${checked ? 'checked' : 'unchecked'}`)
  }

  render() {
    return (
      <div>
        <ul>
          {this.props.studentData.map(item =>
            <Child key={item.id} {...item} onChange={this.handleChange} />
          )}
        </ul>
      </div>
    )
  }
}

const studentData = [
  { id: 1, name: 'Student 1' },
  { id: 2, name: 'Student 2' },
  { id: 3, name: 'Student 3' },
]


ReactDOM.render(
  <Parent studentData={studentData} />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Post a Comment for "Return Checked Value From Child To Parent And To Grandparent Component Using React"