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?

1
  • 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. Commented Nov 15, 2017 at 10:44

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

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 absolutely. As long as you keep propagating the callback.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.