someuser2491
someuser2491

Reputation: 1968

How to refactor code using styled components in react and typescript?

i want to refactor code for the styled components using react and typescript.

i have two link black and blue sharing same css and some style differ.

below is the code,

return (
    <Wrapper>
        <ButtonLink a="someurl">
            black
        </ButtonLink>
        <ButtonLink a="url">
            blue
        </ButtonLink>
    </Wrapper>
);


const ButtonLink = styled.a`
    border: none;
    background: none;
    display: flex;
    justify-content: center;
    align-items: center;
`;

Now for the black link i want to add background-color: black and for blue link i want to add the background-color blue.

how can i add these styles to those two links using styled components. could someone help me with this. thanks.

Upvotes: 0

Views: 330

Answers (3)

kvek
kvek

Reputation: 546

You could use props in your styled component

const ButtonLink = styled.a`
    border: none;
    background: ${props => props.bgColor};
    display: flex;
    justify-content: center;
    align-items: center;`

Then pass in the props like this

return (
  <Wrapper>
     <ButtonLink a="someurl" bgColor="black">
         black
     </ButtonLink>
     <ButtonLink a="url" bgColor="blue">
         blue
     </ButtonLink>
  </Wrapper>
);

Alternatively if you don't want to pass in props you could extend the initial ButtonLink component

const ButtonLink = styled.a`
    border: none;
    display: flex;
    justify-content: center;
    align-items: center;`


const BlueButtonLink = styled(ButtonLink)`
    background-color: #0000FF;`

const BlackButtonLink = styled(ButtonLink)`
    background-color: #000;`


return (
  <Wrapper>
     <BlackButtonLink a="someurl">
         black
     </BlackButtonLink>
     <BlueButtonLink a="url" >
         blue
     </BlueButtonLink>
  </Wrapper>
);

Upvotes: 1

johannchopin
johannchopin

Reputation: 14844

Just add add the color as a props of your ButtonLink component. But don't forget to add the interface for it since you are using TypeScript:

return (
    <Wrapper>
        <ButtonLink color="black" a="someurl">
            black
        </ButtonLink>
        <ButtonLink color="blue" a="url">
            blue
        </ButtonLink>
    </Wrapper>
);

interface ButtonLinkProps {
    color: string
}  

const ButtonLink = styled.a<ButtonLinkProps>`
    color: ${props => props.color}
    border: none;
    background: none;
    display: flex;
    justify-content: center;
    align-items: center;
`;

Upvotes: 0

Robert Sidzinka
Robert Sidzinka

Reputation: 828

You need to pass properties as a props to your components, for example

<ButtonLink color="red" href="#">Red</ButtonLink>
const ButtonLink = styled.a`
  ...,
  color: ${props => props.color}
`

Upvotes: 2

Related Questions