Search code examples
javascriptcssreactjsinputstyled-components

image to left of placeholder in styled.input react


i am trying to achieve this design: goalimg

and this is what i have so far: currentimg

I need to have the search icon display to the left of the placeholder text in this input. I am using a styled input component in react javascript. This is my CSS style for the input:

const SearchBar = styled.input`
color: #000000;
margin-top: 20px;
background: #F2F2F7;
padding-left: 35.33px;
border-radius: 50px;
height: 30px;

border: 1px solid ${props => props.theme.gray2};
padding-top: 7px;
padding-bottom: 7px;
margin-left: 14px;
margin-right: 14px;
outline-width: 1px;
display: flex;
flex-direction: row;

`;

and this is in the render() method:

<SearchBar placeholder="Search Chats"></SearchBar>

How can I place the image in the input to the left of the placeholder text?


Solution

  • in your index.html (or where ever you are rendering your app to) add to the head:

    <head>
       <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    </head>
    <div id="app"></div>
    

    in your React file add:

     <span className='search-bar'>
        <i className="fa fa-search" aria-hidden="true"></i>
        <input></input>
     </span>
    

    in your Css file add:

    .search-bar { 
      position: relative;
      input { padding: 12px; }
      .fa-search { 
        position: absolute; 
        padding: 12px;
        top: 2px; 
        left: 5px; 
        z-index: 1; 
      }
    }
    

    or, instead of padding, you can use

    .fa-search { 
      position: absolute; 
      top: 2px; 
      left: 5px; 
      z-index: 1; 
    }
    

    Adjust the top & left value to position it exactly.

    Plus any other styling to the input.

    you can access many icons here: link