Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve tag agnostic styled components?

If I want a button but, only the presentational part of that, so if I do:

import styled from 'styled-components'

const Button = styled.button`
  color: red;
  text-align: center;
`

I'm forced to render a button tag, but what about if semantically I need an anchor?

like image 407
cl0udw4lk3r Avatar asked Feb 13 '17 12:02

cl0udw4lk3r


People also ask

Can I pass Props to styled component?

Passed propsIf the styled target is a simple element (e.g. styled. div), styled-components passes through any known HTML attribute to the DOM. If it is a custom React component (e.g. styled(MyComponent)), styled-components passes through all props.

Can I use material UI with styled-components?

Just to give you an overview, Material UI doesn't limit you to only JSS based styling. If you love using Styled-Components or CSS modules, you have the freedom to use it with Material UI.

Is it good to use styled-components?

Advantages of using Styled-components Below are some of benefits of using styled-components: Eliminates class name bugs: styled-components provide unique class names for your styles, thus eliminating the problems with class names duplications, misspellings, and overlaps.


1 Answers

styled-components provides withComponent that'll be useful for cases where you want to use an a different tag with a component. This is similar to @siddharthkp's answer in function, but uses the API.

Example from the documentation:

const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// We're replacing the <button> tag with an <a> tag, but reuse all the same styles
const Link = Button.withComponent('a')

// Use .withComponent together with .extend to both change the tag and use additional styles
const TomatoLink = Link.extend`
  color: tomato;
  border-color: tomato;
`;

render(
  <div>
    <Button>Normal Button</Button>
    <Link>Normal Link</Link>
    <TomatoLink>Tomato Link</TomatoLink>
  </div>
);
like image 84
typeoneerror Avatar answered Sep 29 '22 11:09

typeoneerror