Extending Components in rebass.js?

300 Views Asked by At

Beginner here. As of now I can use Box like so:

<Box
  p={5}
  fontSize={4}
  width={[ 1, 1, 1/2 ]}
  color='white'
  bg='magenta'>
  Box
</Box>

and give it certain specified props, as it says on the site:

All margin and padding props
width: responsive width
fontSize: responsive font size
color: text color
bg: background color
flex: CSS flex shorthand property
order: CSS order property
alignSelf: CSS align-self property

Question: What if I need more props?

I know that I can extend rebass components, however, this seems to hard-code certain CSS properties into the component. E.g. If my Box is always purple I can create PurpleBox and save the color there. Or on their website there is this example:

const Container = props =>
  <Box
    {...props}
    mx='auto'
    css={{
      maxWidth: '1024px'
    }}
  />

Fair enough! What what of I need to create a component, say, PositionedBox which gets an additional position prop for relative or absolute positioning?

I would like to use it like so:

<Box
  p={5}
  fontSize={4}
  width={[ 1, 1, 1/2 ]}
  color='white'
  bg='magenta'
  position='abs'>
  Box
</Box>

Is this possible? Not sure how I could accomplish this.

1

There are 1 best solutions below

0
On

You could make use of styled-components and styled-system

import styled from "styled-components";
import { position } from "styled-system";

// through interpolation

const StyledBox = styled(Box)`
 // some properties
    ${position}
`;

// passing as a single property
const StyledBox = styled(Box)(position);

passing multiple properties

import { compose, property1, property2, ... } from "styled-system";

import StyledBox = styled(Box)(compose(property1, property2, ....));

this would extend all the position properties supported by the styled system. list of all the out-of-the-box properties supported by styled-system here