Search code examples
reactjsstyled-components

how to change image src using props with styled component and react


I want to reuse my component for multiple pages. so, I have to change img src in styled.img component as passing props.

is it possible to change image src on styled component ?

I applied my code like below. it's not working..

//logic

import Myimg from './img/icon_my';

const OngoingLists = ({ ...props }) => {
  return (
    <ListsOutWrap>
      <ProgramListWrap {...props}>
        <IconWrap {...props} >
          <MyIcon {...props} />
        </IconWrap>
      </<ProgramListWrap>
    </ListsOutWrap>
  );
}


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

I tried like above, any image doesn't show...even default img file doesn't show.. how can I change src file by using props ?? should I use background-image ?

thanks for ur help in advance ! :)


Solution

  • 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;
    `;