How to extend styling of component without using wrapper element?

312 views Asked by At

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?

1

There are 1 answers

0
kind user On BEST ANSWER

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:

  • you could assign a className to Atom, so you can adjust/overwrite the styles with CSS

  • pass the extraStyles props to Atom and then pass to the styled component and just use inside after the previous, default styles to overwrite them

  • or either pass some extraStyles as CSSProperties object and just use them as inline styling.

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>
  );
};