javascriptreactjsstyled-componentsatomic-design

How to extend styling of component without using wrapper element?


I'm working with styled-components in atomic system. I have my <Atom title={title} onClick={onClick}/> And I have molecule that extends that atom, by just adding some functionality to it without wrapping element:

const Molecule = ({}) => {
  const [title, setTitle] = useState('Base title')

  const onClick = () => {
    // some actions
  }

  useEffect(()=>{
    setTitle('New title')
  },[conditions changed])

  return(
    <Atom title={title} onClick={onClick}/>
  )
}

I have base styling in <Atom/> but I would like to add some more to it in <Molecule/>. Is it possible to do it without creating extra wrapper?


Solution

  • It is possible, but the question is if it's worthy the effort - the most anticipated way would be to do it as the documentation says - to wrap the styled component and extend the styles (but this is what you want to avoid). So either:

    https://codesandbox.io/s/withered-leftpad-znip6b?file=/src/App.js:64-545

    /* styles.css */
    .extraClass {
      color: green;
    }
    
    const AtomStyled = styled.div`
      font-size: 17px;
      color: blue;
      font-weight: 600;
    `;
    
    const Atom = ({ children, className, extraStyles }) => {
      return (
        <AtomStyled style={extraStyles} className={className}>
          {children}
        </AtomStyled>
      );
    };
    
    const Molecule = () => {
      return (
        <Atom className={'extraClass'} extraStyles={{ fontSize: 27 }}>
          Atom
        </Atom>
      );
    };