Search code examples
reactjsstyled-components

React create one styled components for two different icons?


So I am using react icons and I have two different icons that I am styling with styled components. My issue is that they essentially have the exact same styles, but the only difference is which icon I am choosing to style.

I don't know how to combine both icons into one styled component

Here is my code

      const backArrow = styled(IoArrowBack)`
        width: 50px;
        height: 50px;
      `;

      const forwardArrow = styled(IoArrowForward)`
        width: 50px;
        height: 50px;
      `;

Since I am using styled components, I just pass the icon into the () based on which one I want to style. The issue is I have over 12 lines of the exact same styles for both icons. It doesn't make sense to repeat the exact styles

How would I create one styled component, but display two different icons?

Example concept like this

 const arrowIcon = styled(IoArrowBack, IoArrowForward)`
    width: 50px;
    height: 50px;
 `

But then the issue occurs if I were to add them to my JSX

Cause then how would I even add the code?

I can't do

  <arrrowIcon>Back arrow</arrowIcon>
  <arrrowIcon>Forward arrow</arrowIcon>

So it wouldn't know which icon is which.

Is this even possible with styled components, or would I just have to copy and paste the same styles for each icon?


Solution

  • This piece of code is a bit weird to me, I think this is not a valid code

    const arrowIcon = styled(IoArrowBack, IoArrowForward)`
            width: 50px;
            height: 50px;
         `
    

    However you can do a trick to get a shared style

    const sharedIconStyle = css`
                width: 50px;
                height: 50px;
    `
    

    And

       const styledArowBack= styled(IoArrowBack)`
           ${sharedIconStyle}
          `   
       const styledArrowForward = styled(IoArrowForward)`
           ${sharedIconStyle}
          `;