Aaron Christiansen
Aaron Christiansen

Reputation: 11837

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

Upvotes: 7

Views: 5096

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 38046

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');

Upvotes: 9

Simon H&#228;nisch
Simon H&#228;nisch

Reputation: 4968

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).

Upvotes: 4

Related Questions