Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styled-components: extend styles and change element type

Imagine I have the following styles:

color: black;
border: 1px solid white;

and I want to apply them both to two elements of different types:

const SomeImg = styled.img`
  margin: 2em;
`;

const SomeDiv = styled.div`
  margin: 3em;
`;

How can I make both elements extend those styles?


It's easy enough if they were both <div> or <img>. I could do:

const ExtendMe = styled.div`
  color: black;
  border: 1px solid white;
`;

const SomeDiv = styled(ExtendMe)`
  margin: 2em;
`;

const OtherDiv = styled(ExtendMe)`
  margin: 3em;
`;
like image 933
abagshaw Avatar asked Apr 20 '19 19:04

abagshaw


People also ask

How can you apply dynamic styles to styled-components?

One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals. Our current example is testing to see if our use pointer prop is true.

Can you style already existing components with styled-components?

If you wish to style your own existing (or any third-party) React component, then you can simply use the styled-components' styled() constructor. This works as long as the React component you're styling attaches the passed className prop (or style prop, if you're using react-native ) to the DOM element.

How do you override style styled-components?

You can override an existing styled-components component by passing it to the styled() constructor/wrapper. For example, suppose you have the following styled button element: const Button = styled.

Can you add Classnames to styled-components?

Finally, you can use styled-components with any CSS framework. For example, let's create a Button component with Bootstrap styling. We used the attrs method to add a className attribute to the component with btn btn-primary value.


1 Answers

You can use prop "as" from styled-components who will change html tag of your component: https://www.styled-components.com/docs/api#as-polymorphic-prop

Below an example of what you want:

const ExtendMe = styled.div`
  color: black;
  border: 1px solid white;
`;

const SomeImg = styled(ExtendMe).attrs({
  as: "img"
})`
  margin: 2em;
`;


const SomeDiv = styled(ExtendMe)`
  margin: 3em;
`;

You can see on : https://codesandbox.io/embed/mj3j1xp6pj?fontsize=14

like image 117
Deve Avatar answered Oct 06 '22 12:10

Deve