score:3

Accepted answer

So as I thought there was an easy answer to my problem but I just did not understand some key concepts of React.

I've read up on state and props and decided that I need to to pass data from my child to my parent.

For this I defined a callback function in my main file (App.js):

getAutosuggestInput(value){
    // Test logging:
    console.log(value);
    this.setState({myfieldname: value})
}

Then I passed the function to my component in autosuggest.js:

<Autosuggest
    getInputData={this.getAutosuggestInput}
/>

In my autosuggest component I called the function inside of the event handler which handles changes. You have to use this.props.functionName here where functionName is the function in the parent:

handleChange(event, { newValue }) {
    this.setState({
        value: newValue,
    });
    this.props.getInputData(newValue);
    console.log("New input value:", newValue);
};

So like that I have a function in my parent that sets the textfield value to what was just entered by the user, the value itself comes from the child components handleChange handler which passes the value to my parent. Looks easy when you know what you do but let my tell you it was hard for me :)

score:1

You have the right idea. I have no experience with the react-autosuggest library but based on the documentation, you need to pass in your onChange method via the inputProps object that the component takes. This might work:

const inputProps = { onChange: this.onChange, name:'textBoxValue' , textBoxValue:this.state.value} 

then pass the inputProps object to your AutoSuggest component. Using the example you provided, it would look something like:

<Autosuggest inputProps={this.inputProps} />

Your example is slightly more complicated than what is provided in the documentation for this component because you're setting the value of the textbox to a state value that's equal to the name of the textbox. That's ideal if you have multiple textboxes in the same component, otherwise you could change your onChange method to set the value of the textbox to a state variable named value and pass that in via the inputProps object.

For more information, take a look at the example provided at https://github.com/moroshko/react-autosuggest#installation - specifically what's going on in the render and onChange methods. Hope this helps. Good luck!


Related Query

More Query from same tag