0

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!

8
  • P.S. By "failing me", I mean it doesn't return anything at all Commented Jun 4, 2020 at 19:04
  • 1
    you are not storing your data anywhere for later retrieval. Commented Jun 4, 2020 at 19:05
  • How do I store data in the Parent Class? Commented Jun 4, 2020 at 19:07
  • this.props.passData(suggestions); don't use this in functional component like Child. It gets props as a paramater so it should be props.passData(suggestions);. :) Commented Jun 4, 2020 at 19:08
  • @Deykun I just updated my code and it seems like the data is flowing to the Parent Class but there's one more problem: it only works when I console.log(suggestions) but not with return suggestions Commented Jun 4, 2020 at 19:17

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.