'Style-components - inherit the styles and dynamic props from a styled component but not the tag

Essentially, I am looking for a way to share a spacing styling to all components like this.

const Spacing = styled.div`
    padding: ${props => props.p || 0};
    padding-top: ${props => props.pt || 0};
`;
const Button = styled(Spacing)`
    background: white;
`;

With this example, I can inherit the dynamic padding of Spacing but the problem is it will inherit the tag. so if I use <Button as='button' pt='2rem' > Click </Button> I have to manually add as='' attribute to all inheriting component.

Is there a way to get rid of the as='' attribute?



Solution 1:[1]

I got the solution.

First create the styles to be inherited:

spacing.js

import { css } from "styled-components";

export const Spacing = css`
    margin-top: ${props => props.mt + "rem" || 0};
    margin-bottom: ${props => props.mb + "rem" || 0};
    margin-left: ${props => props.ml + "rem" || 0};
    margin-right: ${props => props.mr + "rem" || 0};
`;

styled.button.js

import styled from "styled-components";
import { Spacing } from "./path-to-spacing.js"

const Button = styled.button`
    ${Spacing};
    // your styles
`;

usage

<Button mt={4}> Click me </Button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric Echemane