score:9

Accepted answer

Styled components are still just react components, and you can simply provide a default prop value in the case a src prop isn't passed when used.

import Myimg from './img/icon_my';

const MyIcon = styled.img`
  width: 100%;
`;

MyIcon.defaultProps = {
  src: Myimg,
};

Usage:

<MyIcon /> // uses default Myimg
<MyIcon src="/path/to/sourceImage" /> // uses "/path/to/sourceImage"

Edit charming-sunset-fpd6c

BTW Correct attrs format to accept props would be to define a function taking props and returning an object:

const MyIcon = styled.img.attrs(props => ({
  src: props.Img || Myimg,
}))`
  width: 100px;
`;

Related Query

More Query from same tag