Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share the same styles between two types of component with React Styled Components

I would like to apply exactly the same styles to a styled input element and a styled select element.

Currently, I'm using string interpolation to do this:

const styles = `
    background-color: white;
    width: 100%;
    border: 0 solid transparent;
    border-radius: 10px;
    margin-bottom: 20px;
    padding-top: 5px;
    padding-bottom: 5px;
    font-size: 1.2rem;
`

const Select = styled.select`${styles}`
const Input = styled.input`${styles}`

Is there a better way of doing this which doesn't involve using a 'raw' string? The disadvantage of using the raw styles string is that Visual Studio Code doesn't syntax-highlight it:

enter image description here

like image 285
Aaron Christiansen Avatar asked Sep 04 '18 09:09

Aaron Christiansen


People also ask

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.

Can you style a styled-component?

Styled Components allow you to style any custom component that you've created. First, the custom component must receive the prop className and pass it to the underlying DOM element. Once that is done, pass the custom component to the styled function and invoke it as a Tagged Template to receive a new Styled Component.


2 Answers

You have few options here:

css helper function:

const styles = css`
  background-color: white;
  // ...
`;

const Select = styled.select`${styles}`;
const Input = styled.input`${styles}`;

"as" polymorphic prop (added in v4):

<Select as="input">
  ...
</Select>

withComponent method (candidate for deprecation):

const Select = styled.select`
  background-color: white;
  // ...
`;
const Input = Select.withComponent('input');
like image 170
Aleksey L. Avatar answered Sep 28 '22 08:09

Aleksey L.


You can use the css tagged template literal:

import styled, { css } from "styled-components";

const styles = css`
  background-color: white;
  width: 100%;
`;

const Select = styled.select`${styles}`;
const Input = styled.input`${styles}`;

That should get properly syntax highlighted (haven't tested).

like image 39
Simon Hänisch Avatar answered Sep 28 '22 10:09

Simon Hänisch