cdmt
cdmt

Reputation: 913

Styled Components - use styled component as base for another component

I thought this was possible with styled components

Using the first styled Component Block as the bases for another component like

export const BlockOne = styled.Block

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import styled from 'styled-components'

export const Block = styled.div`
  width: 100px;
  height: 100px;
  background: red;
`

export const BlockOne = styled.Block`
  background: yellow;
`

const App = () => {
  return (
    <div>
      <Block/>
      <BlockOne/>
    </div>
  );
}

render(<App />, document.getElementById('root'));

Is there a way to do this

Upvotes: 5

Views: 3329

Answers (1)

jperl
jperl

Reputation: 5112

Yes, like this

export const BlockOne = styled(Block)`
  background: yellow;
`

styled-component only has basic components (tags such as div, span, etc.) as attributes. For anything else, you pass it as a prop.

If you pass a custom component to it, make sure that it accepts a className and that it passes it down to a div or something:

const MyComponent = ({className}) => {
  return <div className={className}></div> // styled-component will use this classname to apply the style
}

export const MyStyledComponent = styled(MyComponent)`
  background: yellow;
`

Else it would have no effect.

Upvotes: 7

Related Questions