question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Autocomplete] Option is invisible when rendering from StyledAutocomplete

See original GitHub issue

Duplicates

  • I have searched the existing issues

Latest version

  • I have tested the latest version

Current behavior 😯

When I select an option from the list, it does not show the selected option.

Using console.log on the state I see that it does indeed select the option, it just does not show it. It also makes the clear button unavailable immediately. So probably it selects it very quickly and removes it from the input field. If I click on the same item twice, it shows it while throwing an error and right until I start filling another field.

This behaviour only occurs with the styledAutocomplete and when the onChange function is active. The onChange function just gets the value and sends it to the parent component. The styled function const StyledAutocomplete = styled(Autocomplete)({}) may even be empty without any added style and the behaviour is the same. The label and the value of the options items are of type string.

Here is a CodeSandbox link: https://codesandbox.io/s/countryselect-material-demo-forked-fimtrw?file=/DestinationsInput.js Here is the code for the component:

  const [destinations, setDestinations] = useState([]);
  const [selectOptions, setSelectOptions] = useState([]);

  const handleFromChange = (event, item) => {
    onFromDestinationChange(item.value);
  };

  const fetchData = async () => {
    try {
      const { data } = await axios.get(url);
      setDestinations(data);
      const options = data.map((item) => ({
        value: item.id,
        label: item.destinations
      }));

      setSelectOptions(options);
    } catch (error) {}
  };

  useEffect(() => {
    fetchData();
  }, []);

  //style MUI component
  const StyledAutocomplete = styled(Autocomplete)({
    ".MuiAutocomplete-inputRoot": {
      color: "#333",
      fontFamily: "Zona Pro Bold",
      fontWeight: 700,
      fontSize: "16px",
      ".MuiAutocomplete-input": {
        paddingLeft: "2rem"
      }
    }
  });

  return (
    <div className="searchDestinationsContainer">
      <div className="searchField">
        <StyledAutocomplete
          disablePortal
          id="from-destination"
          options={selectOptions}
          sx={{
            width: "100%",
            bgcolor: "#EDEDED"
          }}
          renderInput={(params) => (
            <TextField {...params} placeholder="Flying From" />
          )}
          onChange={handleFromChange}
          autoHighlight={true}
          autoSelect={true}
        />
      </div>
    </div>
  );
}

If I return the normal Autocomplete component, it works fine. If I return the StyledAutocomplete component without the onChange function, it works fine.

Expected behavior 🤔

The expected behaviour should be that when I select an option from the list, it remains on the input field and visible until I change it. I just want to add some padding to the placeholder and change its font and colour. Not sure why it doesn’t work even with the styled function empty. Maybe something to do with the onChange prop that does not work well with StyledAutocomplete?

Steps to reproduce 🕹

Steps:

  1. In the DestinationsInput component: Remove the StyledAutocomplete and use the Autocomplete component from MUI and check the normal behaviour.
  2. Add the StyledAutocomplete component and check what happens when selecting an option.
  3. Remove the onChange function from the StyledAutocomplete and check behaviour.
  4. Add back the onChange function and remove all styling options from the styles function and check behaviour of the StyledAutocomplete behaviour.

Context 🔦

I am trying to style the Autocomplete input by adding padding, color and background. Mostly to the text and placeholder.

https://codesandbox.io/s/countryselect-material-demo-forked-fimtrw?file=/DestinationsInput.js

Your environment 🌎

`npx @mui/envinfo`
  Google Chrome.
    System:
    OS: macOS 12.2.1
  Binaries:
    Node: 16.14.0 - /usr/local/bin/node
    Yarn: Not Found
    npm: 8.3.1 - /usr/local/bin/npm
  Browsers:
    Chrome: 99.0.4844.74
    Edge: Not Found
    Firefox: 98.0
    Safari: 15.3
  npmPackages:
    @emotion/react: ^11.8.2 => 11.8.2 
    @emotion/styled: ^11.8.1 => 11.8.1 
    @mui/base:  5.0.0-alpha.72 
    @mui/lab: ^5.0.0-alpha.73 => 5.0.0-alpha.73 
    @mui/material: ^5.5.1 => 5.5.1 
    @mui/private-theming:  5.4.4 
    @mui/styled-engine:  5.4.4 
    @mui/styled-engine-sc: ^5.4.2 => 5.4.2 
    @mui/system:  5.5.1 
    @mui/types:  7.1.3 
    @mui/utils:  5.4.4 
    @types/react:  17.0.40 
    react: ^17.0.1 => 17.0.2 
    react-dom: ^17.0.1 => 17.0.2 
    styled-components: ^5.3.3 => 5.3.3 
    typescript: ^3.9.10 => 3.9.10 

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
kiurious-designcocommented, Mar 21, 2022

@jsar3004 This works, thank you!

1reaction
jsar3004commented, Mar 19, 2022

Try using a arrow function .For eg Change code from onChange={handleFromChange} to onChange={()=>handleFromChange}

Read more comments on GitHub >

github_iconTop Results From Across the Web

Autocomplete not rendering as expected Material UI
Two issues seem to be intertwined. First, the Autocomplete options don't seem to be all rendering. There are up to 10 results (limited...
Read more >
Autocomplete API - Material UI - MUI
Name Type Default options * array renderInput * func autoComplete bool false
Read more >
Customize MUI Autocomplete with getOptionLabel ...
Learn how to use getOptionLabel, renderInput, and renderOption in Material-UI's Autocomplete. We'll also custom style the component and ...
Read more >
Customizing the Material-UI Autocomplete Component
Therefore, I created this demo that fetches data from a Star Wars API and populates this custom styled Autocomplete component.
Read more >
Autocomplete — Granite UI 1.0 documentation
/libs/granite/ui/components/coral/foundation/form/autocomplete. Warning ... The renderer to render the user selections (given by the options renderer).
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found