Friday, February 12, 2021

sneaking in a background image on an arbitrary storybook standalone doc

To misquote an old musical:

I'm just a dev who can't say no,
I'm in a terrible fix,
I always say 'C'mon, let's go!'
when I just oughta say 'Nix!'

Anyway. A designer wondered if we could put in a background image on a specific standalone doc. Here's the typescript object I came up with:

export type StorybookStyleInjectorProps = {
  property: string;
  value: string;
};

export const StorybookStyleInjector = ({
  property,
  value
}: StorybookStyleInjectorProps) => {
  const elems = Array.prototype.slice.call( 
  	document.getElementsByClassName('sbdocs-wrapper') );
  setTimeout(() => {
    for(const elem of elems) {
      elem.style[property] = value;
    }
  }, 0);
  return null;
};

export default StorybookStyleInjector;
I had to use setTimeout for unclear reasons regarding rendering... 

Sample usage:

<StorybookStyleInjector
  property='backgroundImage'
  value='url(/images/introduction/bg-pattern.svg)'
/>
Lets see if my PR gets approved....

No comments:

Post a Comment