Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new component and inherit styles from styled-component

const Button = styled.button`
  display: inline-block;
  width: 300px;
  background-color: black;
`    

const ButtonHref = styled.a`
  ${Button}
`   

So I have two styled-components. I want to inherit 'Button' styles but create another tag. I use react-emotion. How can I do this?

like image 742
Lamer_2005 Avatar asked Apr 30 '19 08:04

Lamer_2005


People also ask

Does styled-components generate CSS?

Existing CSSstyled-components generates an actual stylesheet with classes, and attaches those classes to the DOM nodes of styled components via the className prop. It injects the generated stylesheet at the end of the head of the document during runtime.

Can you use Classnames with styled-components?

The styled method works perfectly on all of your own or any third-party component, as long as they attach the passed className prop to a DOM element.

Can you pass props to styled-component?

Passed propsIf the styled target is a simple element (e.g. styled.div), styled-components passes through any known HTML attribute to the DOM. If it is a custom React component (e.g. styled(MyComponent)), styled-components passes through all props.


1 Answers

There are a few options here, using composition, styled components, or with props. The second option is probably what you want, but I've provided two other options as well.

1. Using composition

const baseButton = css`
  color: white;
  background-color: black;
`

const fancyButton = css`
  background-color: red;
`

render() {

  return (
    <div>
      <button css={baseButton}></button>
     <button css={[baseButton, fancyButton]}></button>
    </div>
  )
}

The second button will have the baseButton and specialButton styles.

Or...

const baseButton = css`
 color: white;
 background-color: black;
`

const fancyButton = css`
 ${baseButton};
 background-color: red;
`

render() {
 return (
   <div>
     <button css={baseButton}></button>
     <button css={fancyButton}></button>
   </div>
 )
}

2. Using styled components

const Button = styled.button`
  color: white;
  background-color: black;
`
const Fancy = styled(Button)`
  background-color: red;
`

render() {
  return (
    <div>
      <Button>Button</Button>
      <Fancy>Fancy</Fancy>
    </div>
  )
}

This works for any component that accepts the className prop, which button does.

3. Using props

  const Button = styled.button`
    color: white;
    background-color: ${props => props.fancy ? 'red' : 'black'};
  `

  render() {
    return (
      <div>
        <Button>Button</Button>
        <Button fancy>Fancy</Button>
      </div>
    )
  )
like image 174
Brett DeWoody Avatar answered Oct 21 '22 10:10

Brett DeWoody