score:2

as tried to explain in the comments you can use callbacks for this, but try to avoid to get a value from child component like that. you can keep selected state in your parent component. your item component does not need to keep a state at all for this. with proper handlers from the parent, you can update your state easily.

class app extends react.component {
  state = {
    items: [
      { id: "1", name: "foo", quantity: 1 },
      { id: "2", name: "bar", quantity: 2  },
      { id: "3", name: "baz", quantity: 3 },
    ],
    selected: "",
  }

  handleselect = item => this.setstate({ selected: item.id })

  render() {
    const { items } = this.state;
    
    return (
      <div>
      selected item: {this.state.selected}
      {
        items.map( item =>
          <item key={item.id} item={item} onselect={this.handleselect} />
        )
      }
      </div>
    );
  }
}

const item = props => {
  const { item, onselect } = props;
  const handleselect = () => onselect( item );
  
  return (
    <div style={{border: "1px solid gray"}} onclick={handleselect}>
      <p><strong>item id:</strong> {item.id}</p>
      <p><strong>item name</strong>: {item.name}</p>
      <p><strong>item quantity</strong>: {item.quantity}</p>
    </div>
  )
}

reactdom.render(<app />, 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>

score:3

passing props from child to parent component works using callback functions in react. or you can also use state management library like redux and store the data in child component and get the data in parent component.

the example below illustrate how to send props from child to parent. i am sharing below example to make you understand how you can send props from child to parent.

itemselection: parent component

      //handler function
      getpropsfromchild = (id, name) => {
            console.log(id, name);
       }

       //pass down your handler function to child component as a prop
        <div classname="row">
            {this.state.items.map(i => <item ref="item" id={i.id} name={i.name} getpropsfromchild={this.getpropsfromchild} quantity={i.quantity} />)}
        </div>

item: child component

componentdidmount(){
    //access handler function passed to your item component and access it using this.props and send the values as you want to the function
    this.props.getpropsfromchild(“01”, “hi”);
}

Related Query

More Query from same tag