Search code examples
cssreactjsstylesz-index

Suggestions dropdown in reactJS and material UI not working using zIndex


I am trying to make a dropdown menu having the names of cities returned from google maps such that it appears on the top of a division below it using z-Index. Here is the minimal code.

class PlacesAutocomplete1 extends React.Component {
  ....

  render() {
    const open = Boolean(anchorEl);
    const { anchorEl } = this.state;
    const searchOptions = {
      types: ['(cities)'],
      componentRestrictions: { country: 'in' }
    }

    return (
      <div>
        <PlacesAutocomplete
          value={this.state.address}
          onChange={this.handleChange}
          onSelect={this.handleSelect}
          searchOptions={searchOptions}
          shouldFetchSuggestions={this.state.address.length > 3}
        >
          {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
            <div style={{ position: 'relative', zIndex: 2 }}>
              <TextField
                id="outlined-search"
                type="search"
                label="city"
                margin="dense"
                onClick={this.handleClick}
                variant="outlined"
                {...getInputProps()}
              />
              <div>
                {loading && <div>Loading...</div>}
                {suggestions.map(suggestion => {
                  const className = suggestion.active
                    ? 'suggestion-item--active'
                    : 'suggestion-item';
                  // inline style for demonstration purpose
                  const style = suggestion.active
                    ? { backgroundColor: '#fafafa', cursor: 'pointer', position: 'relative', zIndex: 2 }
                    : { backgroundColor: '#ffffff', cursor: 'pointer', position: 'relative', zIndex: 2 };
                  return (
                    <Paper {...getSuggestionItemProps(suggestion, {
                      className,
                      style
                    })} elevation={1}>
                      <span>{suggestion.description}</span>
                    </Paper>
                  );
                })}
              </div>
            </div>
          )}
        </PlacesAutocomplete>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <h2>Suggestions Should be on the top of Me</h2>
        </div>
      </div>
    );
  }
}

Can anyone help guide me with what am I doing wrong? Here is the code sandbox demo

Edit optimistic-wood-3vgiw


Solution

  • It works, but you use relative position and it does not overflow with the next block. You should use position: absolute for block with suggestions. Take look at the forked example here https://codesandbox.io/embed/flamboyant-tree-hc1v6