I have a custom built component called Autocomplete that is essentially a text input box, that among other things, gets the user input when its is typed in. It has an onChange handler like this:
class Autocomplete extends Component {
constructor(props) {
super(props);
this.state = {
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: ""
};
}
//Lifted function to reset autocomplete for Reset button
handleReset = () => {
this.setState({
userInput: ""
});
};
//Begin Autocomplete functionality
onChange = e => {
const { suggestions } = this.props;
const userInput = e.currentTarget.value;
const filteredSuggestions = suggestions.filter(
suggestion =>
suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
);
this.setState({
activeSuggestion: 0,
filteredSuggestions,
showSuggestions: true,
userInput: e.currentTarget.value
});
};
....
I use this component in a parent form component like this:
<Autocomplete ref={autoCompleteRef} suggestions={affiliationData}
onChange={myChangeHandler}/>
I am trying to lift the value of the userInput to my hook. I initially tried using useRef in myChangeHandler, but I can't get it to fire inside the parent component:
function AddContactForm() {
const [name, setName] = useState();
const [title, setTitle] = useState();
const [current, setCurrent] = useState();
const [email, setEmail] = useState();
const [phone, setPhone] = useState();
const [county, setCounty] = useState();
const [affiliation, setAffiliation] = useState();
const [centralRegionLead, setCentralRegionLead] = useState("True");
const myChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
if (nam === 'name') {
setName(val);
} else if (nam === 'title') {
setTitle(val);
} else if (nam === 'current') {
setCurrent(val);
} else if (nam === 'email') {
setEmail(val);
} else if (nam === 'phone') {
setPhone(val);
} else if (nam === 'county') {
setCounty(val);
} else if (nam === 'autocomplete') {
const { state } = autoCompleteRef.current;
setAffiliation(state.userInput);
} else if (nam === 'centralRegionLead') {
setCentralRegionLead(val);
}
}
What am I doing wrong here?
So if I understand correctly -- it looks like you're managing the state of the userInput in the child Autocomplete component, and to access userInput in the parent component, you'll have to declare and manage the userInput state in the parent component and pass it to Autocomplete as a prop.
Apologies if I misunderstood...