Search code examples
javascriptreactjsreact-propsdataflowreact-state

Unable to pass data from Child Functional Component to React Parent Component (React.js)


I am building an Autocomplete component in react so I can render individual autocomplete(s) in a single page; I want to render the suggestions from Autocomplete in a separate component.

I tried using

class Parent extends Component {

    getData = (data) => {
        if (data) return data;
    };

    render () {
        <AutoComplete passData={this.getData} />
        // after some other elements
        {this.getData()}
    }

}

and

export const Child = (props) => {
    ...
    const updateSuggestion = (suggestions) => {
        this.props.passData(suggestions);
    }
}

But somehow, it's failing me. To confuse me even more, if I just console.log the retrieved data using the code below, it works perfectly!

getData = (data) => {
    if (data) console.log(data);
};

To complicate things even further, it fails me even if I return a hard-coded element:

getData = (data) => {
    if (data) return <p>Hello</p>;
};

Although it works when I remove if (data)

I'm completely lost as to what's happening here and would appreciate the slightest of help!


Solution

  • You can't use

    {this.getData()}
    

    when component will render for first time these {this.getData()} will not have data

    Instead of returning data you need to use state method that will that will render component again so that your data will show up on inside render see this Post enter link description here