Search code examples
styled-components

Styling a child element in a third-party component


I'm using a 3rd party component named "Dialog" with the render method below. As you can see - the component has more than one className. I'd like to create a styled-component called StyledDialog which contains a prop that lets me override the width associated with the div that has the "SURFACE" className. Can this be done with Styled-Components - or do I need to bring the source code into my app and handle that manually.

render() {
  const { className, children, onClose, open, ...otherProps } = this.props;
  const ariaHiddenProp = open ? {} : { 'aria-hidden': true };

  return (
    <aside
      className={classnames(
        ROOT, 
        {
          [ANIMATING]: this.state.animating,
          [OPEN]: open,
        }, 
        className
      )}
      onClick={(e) => { 
        if (onClose) onClose(e); 
      }}
      onTransitionEnd={() => { 
        this.setState({ animating: false }); 
      }}
      {...ariaHiddenProp}
    >
      <div
        className={SURFACE}
        onClick={(e) => { 
          e.stopPropagation(); 
        }}
        {...otherProps}
      >
        {children}
      </div>
      <div className={BACKDROP} />
    </aside>
  );
}

Solution

  • Based on your explanation, i think you should wrap this 3rd party component with styled method and apply your styles by referencing the corresponding classnames of that component from the wrapped styled component.

    For instance, If the name of existing component is Hello, you can apply styling from a styled-component on any of its DOM children like this:

    const StyledHello = styled(Hello)`
        .${classes.SURFACE} {
            width: 10rem;
            border: 2px solid green;
        }
    `;
    

    Working Demo