Home > other >  How to make Styled components generic to receive parameters?
How to make Styled components generic to receive parameters?

Time:10-22

I'm trying to use Styled Components with React FC. I want to display few details inside a div container, which all has the same stylings. Instead of writing hard coded such as Name: Height: Weight: etc. in the h-tags, can I do it in a more generic way to pass the text as parameter?

This is the way I have implemented, but I am thinking there should be some better way to do it. Like giving a parameter to the Styled component.

const CardContentContainer= styled.div`
  margin: 4px;
  padding: 4px;
  text-align: left;
  font-size: 14px;
`;

const CardContentDetails = styled.h3`
  font-weight: normal;
  color: #fff;
  margin: 8px;
  white-space: nowrap;
`;

this is the code inside the return:

return (

 <CardContentContainer>
    <CardContentDetails>
      Name: {ItemDetails?.name}
    </CardContentDetails>
    <CardContentDetails>
      Height:{ItemDetails?.height}
    </CardContentDetails>
    <CardContentDetails>
      Weight:{ItemDetails?.weight}
    </CardContentDetails>
  </CardContentContainer>
);

CodePudding user response:

You cant pass such props to Styled components because the main point of SC is to apply a custom style to that component. To make it receive some custom props, you have to wrap it inside another component like so...


const StyledTextField = styled(TextField)`
  margin-bottom: 1rem;
  width: 20em;
`;

const Comp: React.FC<{ title: string }> = ({ title }) => (
  <StyledTextField>{title}</StyledTextField>
);

return (
  <Comp titile="some title" />

  • Related