material-ui adding search icon in autocomplete component
Asked Answered
M

5

7

I am using @material-ui autocomplete for search and I want to add search icon next to autocomplete component

I tried something like this but after changing ---- option fields is not displaying

import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
.
.
.
<Autocomplete
      id="combo-box-demo"
      options={this.state.results} // .map((option) => option.title_display)
      getOptionLabel={(option) => option.title}
      style={{ width: 300 }}
      onInputChange={this.handleInputChange}
      renderInput={(params) => (
        <TextField
          {...params}
          variant="outlined"
          InputProps={{
            endAdornment: (
              <InputAdornment>
                <IconButton>
                  <SearchIcon />
                </IconButton>
              </InputAdornment>
            )
          }}
        />
      )}
    />

ANd if I just add searchicon it get added below the autocomplete component

<Fragment>
  <Autocomplete
    id="combo-box-demo"
    options={top100Films}
    getOptionLabel={(option) => option.title}
    style={{ width: 300 }}
    renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" />}
  />
  <SearchIcon />
</Fragment>

https://codesandbox.io/s/material-demo-forked-qt99q?file=/demo.js

Morville answered 21/11, 2020 at 13:47 Comment(0)
S
1

You can use display: "flex" for the parent to align its child in the same line. And also align search icon at the center of the element,

<SearchIcon style={{ cursor: "pointer", padding: "17px" }} />

enter image description here

Hope you are expecting the same use case. Let me know if you are facing any issue.

Sample demo:- https://codesandbox.io/s/material-demo-forked-v17jz?file=/demo.js

Spermous answered 21/11, 2020 at 14:22 Comment(1)
Thank you I was struggling with this all day really appreciate your helpMorville
W
5

[this is output][1] [1]: https://i.sstatic.net/JBSvO.png

import React, { useState, useEffect } from 'react';
import { TextField} from '@material-ui/core'
import InputAdornment from '@material-ui/core/InputAdornment';
import Autocomplete from '@material-ui/lab/Autocomplete';
import SearchIcon from '@material-ui/icons/Search';
import { makeStyles, Theme } from "@material-ui/core/styles";

export default function AddBusiness() {    

    const useStyles = makeStyles((theme: Theme) => ({
     margin: {
        padding: "10px 5px 5px 5px",
        borderRadius: 4,
        backgroundColor: theme.palette.common.white,
        margin: theme.spacing(0),
        border: "1px solid rgb(157, 157, 157)",
        width: "100%",
      },
    }));

    const classes = useStyles();

    const [cityData, setCityData] = React.useState([]);

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/todos')
        .then(data => data.json())
        .then(res => setCityData(res))
        .catch(error => console.log(error))
    }, [])

 return (  
    <Autocomplete
        id="combo-box-demo" 
        options={cityData} 
        getOptionLabel={(option: any) => option.title} 
        className={classes.margin} 
        style={{ paddingBottom: '8px' }} 
        renderInput={(params) => <TextField {...params} label="" 
        placeholder="Search City" 
            InputProps={{ ...params.InputProps, 
            startAdornment: ( <InputAdornment position="start"> <SearchIcon /> 
            </InputAdornment> ),
            disableUnderline: true }} />} 
    />
 )}
Wolfsbane answered 8/9, 2021 at 13:24 Comment(3)
Please explain your solution. Answers which do not have an explanation and are only code get flagged as low effort.Balaton
This is the proper answer for MUI. Dont mess around with styles. Use the given slotsPersnickety
InputProps={{ ...params.InputProps, .. is exactly what I neededGillam
S
1

You can use display: "flex" for the parent to align its child in the same line. And also align search icon at the center of the element,

<SearchIcon style={{ cursor: "pointer", padding: "17px" }} />

enter image description here

Hope you are expecting the same use case. Let me know if you are facing any issue.

Sample demo:- https://codesandbox.io/s/material-demo-forked-v17jz?file=/demo.js

Spermous answered 21/11, 2020 at 14:22 Comment(1)
Thank you I was struggling with this all day really appreciate your helpMorville
R
1

I am writing this in case it is useful to anyone, because I was able to solve it. In my case I solved it by adding the icon to the Textfield.

<Autocomplete 
  options={arrayList}
  renderInput={(params) => 
    <TextField 
       {...params}
       InputProps={{
         ...params.InputProps,
          endAdornment: (
            <Icon icon='material-symbols:search' />
          )
       }}
    />
  } />

As someone commented, if you add it with the "forcePopupIcon" property of the autocomplete, it overwrites the icon to open the listing.

The "endAdornment" property indicates that it has to be added at the end of the input, you can use "startAdornment" in the same way to add it to the left.

Rogelioroger answered 2/6, 2023 at 14:4 Comment(0)
M
-1

This is the way you can customize the popup Icon

<Autocomplete
            className={classes.root}
            id="combo-box-demo"
            options={boards}
            getOptionLabel={(option) => option}
            forcePopupIcon={true}
            popupIcon={<SearchIcon />}
            renderInput={(params) => (
                <>
                    <TextField
                        placeholder="search"
                        {...params}
                        label="Combo box"
                        variant="filled"
                    />
                </>
            )}
        />
Mongeau answered 9/9, 2021 at 15:36 Comment(1)
This is not a correct solution as the search icon will rotate on focus of autocompletePersnickety
C
-1

So basically here search icon will be visible only when anything is not selected if you want to show that every time you can just remove the if condition and just put the search icon tag in StartAdorment. If you have any query just comment down below i will try to solve as soon as possible.

const handleChange = (event: React.ChangeEvent<{}>, newValue: any[]) => {
    setSelectedOptions(newValue);
    handleSetData(service, newValue);
};


return (
        <Autocomplete
            multiple
            options={data}
            limitTags={3}
            disableCloseOnSelect
            getOptionLabel={(option) => option.id}
            value={getResourceData(service) as any[]}
            style={{ width: 'calc((100% - 3% - 250px) / 4)' }}
            onChange={handleChange}
            renderOption={(props, option, { selected }) => <TypeaheadItem {...props} option={option} selected={selected} />}
            renderInput={(params) => (
                <TextField {...params}
                    variant="outlined"
                    label={service}
                    placeholder='Search...'
                    InputProps={{
                        ...params.InputProps,
                        style: { height: '50px', overflow: 'hidden' }, // Keep input field height consistent
                        startAdornment: (selectedOptions.length ? <span style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: '5px'
                        }}>
                            {selectedOptions.length} Selected
                            <Search />
                        </span> : <Search />)
                    }}

                />
            )}
        />
)
Collocutor answered 21/8 at 14:59 Comment(1)
Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.Floris

© 2022 - 2024 — McMap. All rights reserved.