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