简体   繁体   中英

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.

在此处输入图片说明

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

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> /** 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;
}

I got it working by passing a custom component where the svg image is wrapped by an i tag that has a an icon class:

const CustomIcon = (
  <i className="icon">
    <img width={38} height={38} src={searchIcon} />
  </i>
);

const App = () => {
  return (
    <Input icon={CustomIcon} iconPosition="left" placeholder="placeholder" />
  );
};

The benefit to this approach is that you can change the iconPosition without it breaking the styling with this approach.


To give more context the icon getting displayed at the right position is due to the styles applied to this selector: .ui.icon.input>i.icon . Because it expects an i tag the styles won't be applied if you don't wrap the image between i tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM