Home > Blockchain >  Send value to parent function when class renders a child component
Send value to parent function when class renders a child component

Time:02-20

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.

How could I pass the value?

CodePudding user response:

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' });
}
  • Related