Search code examples
javascriptreactjsecmascript-6react-dom

React bubbling up not working


I have a child component and a parent component and I am trying to bubble up some data from the child to the parent like so

Child:

bubbleUp(data){
  alert(data);
  this.props.addToLib(data);
}
...
render() {
  let formattedDate = this.props.releaseDate;
  return (
    <div className="component-search-result-row" onClick={() => {this.bubbleUp(this.props)}}

Parent:

addToLib(data){
    alert(data);
    this.setState({selectedData : data});
}
...
    render(){
    return(
    <SearchResultRow addToLib={() => this.addToLib()}/>
    )};

Now I am getting data from the first alert(the child) but I am getting undefined from the parent. Any idea of what I am missing?


Solution

  • In your render method for your parent:

    render(){
        return(
        <SearchResultRow addToLib={() => this.addToLib()}/>
    )};
    

    Your method does not take in any data, but instead calls this.addToLib() without any arguments.

    If you change it to this: it should work: (note the extra data)

    render(){
        return(
        <SearchResultRow addToLib={(data) => this.addToLib(data)}/>
    )};