How to add icon in search bar in react-autocomplete component

291 views Asked by At

I am using react-autocomplete for search and I want to add search icon to autocomplete component

My current code is

import Autocomplete from "react-autocomplete";
import searchIcon from "../images/search-icon.svg";
......
......

        <InputGroup className="searchbar">
           <div style={{ width: "100%", display: "flex" }}>
              <Autocomplete
                getItemValue={(item) => item.key}
                items={suggestionItems}
                renderItem={(item, isHighlighted) =>
                  <div style={{ background: isHighlighted ? '#eee' : 'transparent' }} key={item.key}>
                    {item.label}
                  </div>
                }
                
                value={queryText}
                onChange={this.onChange}
                onSelect={this.onSelect}
                autoHighlight={false}
                inputProps={{ style: { width: "100%", height: "100%", padding: "6px 12px" }, placeholder: "Enter a query here"}}
                wrapperStyle={{ width: "100%" }}
                ......
                ......
           </div>
        </InputGroup>

My end goal is to have something similar to stackoverflow search bar like below:

enter image description here

I tried to add the search icon inside the placeholder like this:

inputProps={{ style: { width: "100%", height: "100%", padding: "6px 12px" }, placeholder: " Enter a query here"}}

But the icon will disappear when typing..I want the icon stay there inside the search bar no matter what, exactly like what stackoverflow search bar does.

Does anybody know how I can make it work with react-autocomplete ?

Thank you so much!!

1

There are 1 answers

0
Rohit Singh On

If you can inspect the stack Overflow search bar then you'll see the searchIcon is an SVG Image. So basically you can render the search bar with the below pattern

  <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <style>
    input{
      border:none;
      outline:none;
      font-size:16px
    }
    .search-container{
      border:1px solid;
      width:fit-content;
      background:white;
      padding:5px;
      border-radius:5px
    }
  </style>
</head>
<body>
<div class="search-container">
<img src="https://assets.stickpng.com/images/585e4ae1cb11b227491c3393.png" height="15px" widht="15px" alt="a" />
<input type="text" placeholder="Search...."/>
</div>
</body>
</html>

This will do the job enter image description here