Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send value to parent function when class renders a child component

I have a regular class file in react rendering a child component.

class Parent extends React.Component{
  constructor(props){...}

  onBtnClicked = ({index}) => {
    this.setState({ btnIndex:index })
  };


  render(){
    return(
      <Child onBtnClicked={this.onBtnClicked} />
    )
  }
}

In the child, I’m calling a onBtnClicked function and sending a value.

export default Child = (props) => {
  let prop = {...props};
  return(
    <Button onClick={handleDragEnd}> </Button>
  )

  function handleDragEnd() {
    prop.onBtnClicked('87612876');
  }
}

I see that the parent onBtnClicked function is called. But the value is undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How could I pass the value?

>Solution :

You are passing a string to prop.onBtnClicked

prop.onBtnClicked('87612876');

but attempting to destructure an index property, which from a string, is undefined.

onBtnClicked = ({ index }) => { // <-- "87612876".index -> undefined!
  this.setState({ btnIndex: index })
};

Either don’t destructure in the parent callback:

onBtnClicked = (btnIndex) => {
  this.setState({ btnIndex });
};

or pass the value from the child component in an object with index key so the parent’s callback can destructure it:

function handleDragEnd() {
  prop.onBtnClicked({ index: '87612876' });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading