0

I am creating search form with checkboxes and call api URL. I need advise on how to pass selected checkboxes value from child component back to parent component and update the selected value string state. Thanks.

//CheckboxTest.js
import React,{Component} from 'react';


const data=[
   {checked:false, value:'location A'},
   {checked:false, value:'location B'}
   ];

   class CheckboxTest extends Component{
   state={items:[]};

   onCheckChange=(idx)=>{
       const items = this.state.items.concat();
           items[idx].checked = !items[idx].checked;
           this.setState({items});
           this.props.onChange(this.state.items);
   };
   render(){
       return (
         <div>{data.map(item=>(<div>
           <input type="checkbox" checked={item.checked} onChange= {item.onCheckChange} />
           { item.value }
       </div>))}</div>


       );
   }
   }
   export default CheckboxTest;

//App.js

   import CheckboxTest from './CheckboxTest';

   class App extends Component  {

   state={
   items:[],
   itemchecked

   };
   componentDidMount(){
    //call api
    this.runSearch({items});

   }

   //handle checkbox changes
   handleChange(id) {
   //how to set items state here ???

   this.runSearch(id);
   }
   render(){
     return (
     <div className="App">
      <form>

     <CheckboxTest onChange={this.handleChange} checked={this.itemchecked} />

       </form>
     </div>
     );
     }
    }

   export default App;
Vega
  • 27,856
  • 27
  • 95
  • 103
user788448
  • 779
  • 1
  • 14
  • 36
  • https://stackoverflow.com/questions/47305224/return-checked-value-from-child-to-parent-and-to-grandparent-component-using-rea – user788448 Jul 10 '19 at 23:55

1 Answers1

0

In React there is a one-way data flow. All data flows from parents to children. As such, the parent has to own the function (as you have done with your handleChange-function) and the child has to run that function. This last part you have not done.

You need to use the props of the child to access the function you have passed down from the parent. Read more here:

https://reactjs.org/docs/faq-functions.html

ClownBaby
  • 408
  • 6
  • 15
  • After reading this post https://stackoverflow.com/questions/47305224/return-checked-value-from-child-to-parent-and-to-grandparent-component-using-rea, I solved my problem. – user788448 Jul 10 '19 at 23:55