0

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 Component {    
  render() {
    return (
      <div>
        <div>
          <ul>{this.props.studentData.map(item => {
            return(
            <div><Child key={item.id} {...item} /></div>);
          })}
          </ul>
          <button>Submit</button>
        </div>
      </div>
    );
  }
}

export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (
      <li><input type="checkbox"/>{name}</li>
    );
  }
}

I am trying to place a submit button under the list which returns the result of checked student name, one or many. What I don't understand is that how to return the value of student name from the Child component to Parent and all the way to the top of the hierarchy and store in some kind of variable. Is there a way to return values to the parent components i.e the components that make a call?

user8907896
  • 71
  • 1
  • 2
  • 9
  • Pass a function from the parent as a prop of Child and inside Child call this prop when the input is checked. In the parent you will keep a state of the checked Child and then send it on submit. – ChrisR Nov 15 '17 at 10:44

1 Answers1

7

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>
Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
  • Can a `Grandparent` component also retrieve the data from the `Parent` component? Is it possible to get the data from the bottom of the hierarchy to the top no matter the presence of checkboxes and buttons? – user8907896 Nov 15 '17 at 14:26
  • @user8907896 absolutely. As long as you keep propagating the callback. – Hemerson Carlin Nov 15 '17 at 14:26