Search code examples
javascriptcssreactjssvgsemantic-ui

Add svg image as icon for Input of Semantic UI


I'm using Input from Semantic UI in order to create a search input:

import React from 'react';
import { Input } from 'semantic-ui-react';

export default ({ placeholder, onChange }) => {
  return (
    <Input
      icon="search"
      icon={<img src={searchIcon} />}
      iconPosition="left"
      placeholder={placeholder}
      onChange={onChange}
    />
  );
};

It works and looks good.

The problem is that I need to change its icon with an svg image. So the svg is imported in the file and used like this:

import React from 'react';
import { Input } from 'semantic-ui-react';
import searchIcon from '../../assets/icons/searchIcon.svg';

export default ({ placeholder, onChange }) => {
  return (
    <Input
      icon={<img src={searchIcon} />}
      iconPosition="left"
      placeholder={placeholder}
      onChange={onChange}
    />
  );
};

The problem is that it puts the icon outside of the input and on the right side of it. It should be inside the input and on the left part.

enter image description here

There were no styling changes after the svg was added, why isn't it in the same position as the original icon?


Solution

  • Most likely semantic-ui adding special styles when we add some icon by attribute "icon". Semantic-ui-react doesn't support custom icons. :,(

    In the type declaration we can read: /** Optional Icon to display inside the Input. */icon?: any | SemanticShorthandItem<InputProps>

    My proposition: add some styles to CSS, like me in the sandbox

    .input {
      position: relative;
      width: fit-content;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    img {
      position: absolute;
      right: 5px;
      width: 10px;
    }