Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gets icon prop and passing it into styled() function

I am getting icon prop and passing it to styled function to create a stylized icon based on it

const IconComponent = ({ isActive, icon }) => {
   const StyledIcons = styled(icon)`
      fill: #1f6ed4;
      & path {
         fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
      }
   `
   return <StyledIcons isActive={isActive} />
}

it works, but I am getting warnings like below:

console

Is there any other way to create my StyledIcons component and at the same time receive the icon prop ?

like image 849
songhee24 Avatar asked Apr 24 '26 15:04

songhee24


1 Answers

You must move your StyledIcons outside the IconComponent component and use the as prop to pass your icon component:

const StyledIcons = styled.svg`
  fill: #1f6ed4;
  & path {
    fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
  }
`

const IconComponent = ({ isActive, icon }) => {
    
  return <StyledIcons as={icon} isActive={isActive} />
};

Working example

Edit styled-components dynamic component

And if you don't have control over the icon prop and want to avoid the second warning

Warning: React does not recognize the isActive prop on a DOM element...

you can prefix the isActive prop with a dollar sign ($), turning it into a transient prop:

const StyledIcons = styled.svg`
  fill: #1f6ed4;
  & path {
    fill: ${(props) => (props.$isActive ? "#1F6ED4" : "#232323")};
  }
`;

const IconComponent = ({ isActive, icon }) => {
  return <StyledIcons as={icon} $isActive={isActive} />;
};
like image 179
Fraction Avatar answered Apr 27 '26 04:04

Fraction