1
votes

I have a react app with Material UI Auto suggest feature. I have an issue which is when I'm typing a name in the auto suggestion box and select a suggested name by down arrow key, It will selected and will change the input fields value to it. I only need to go through suggested names without selecting it. If I click on a suggested name or hit Enter, then only it should be selected. I put the Code sandbox example down here.

https://codesandbox.io/s/tfgz5

How can I solve this?

2

2 Answers

1
votes

In your onChange method, along with newValue you are also passed the the method that triggered the change. See the documentation here.

This means that you can check so that you only update the state (which is used to determine what value to be shown) when the user types, clicks or presses enter. In other words, we ignore changes that happens due to up- or down-presses.

So your example could be modified (around line 155) to be

  const handleChange = name => (event, { newValue, method }) => {
    const shouldUpdateSelectedValue = method === "type" || method === "enter" || method === "click";
    shouldUpdateSelectedValue && setState({
      ...state,
      [name]: newValue,
    });
  };

A modified version of you code is available here: https://codesandbox.io/s/material-demo-hcmzl

1
votes

You have to define an onBlur() event handler on the inputProps object of your Autosuggest component. Here is an example:

// The onBlur event handler method
const handleOnBlur = (name) => (event) => {
    if (suggestions.findIndex((s) => s.label === event.target.value) === -1) {
        setState({ ...state, [name]: "" });
        event.target.value = "";
    }
};
<Autosuggest
    {...autosuggestProps}
    inputProps={{
        onChange: handleChange("single"),
        onBlur: handleOnBlur("single") // Add this line
    }}
...


<Autosuggest
    {...autosuggestProps}
    inputProps={{
        onChange: handleChange("popper"),
        onBlur: handleOnBlur("popper") // Add this line
    }}
...

FInd a modified version of your code on this code https://codesandbox.io/s/material-demo-forked-4qidj?file=/demo.js