Search code examples
sharepoint-onlinespfx

Is it possible to pass values from properties to CSS in SPFx?


Is it possible to have a web part in SPFx which has (for example) a property "divWidth" and it be a numeric value in px. Then then a div renders with the width specified in the web part?

I know you could probably do it with inline styles but can you pass the value to an SCSS file? Thanks P


Solution

  • Create the CSS Variables, for example based on the web part properties

    let styleBlock = { "--tileWidth": this.props.width + "px",
     "--tileHeight": this.props.height + "px" } as React.CSSProperties;
    

    render it like:

     <div className={`${styles.linkTiles} ${styles.tileCont}`} style={styleBlock}>
    

    css will be like:

    .linkTiles {
      &.tileCont {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        justify-content: left;
      }
     
      .tile,
      .tileFlip,
      .tileFront,
      .tileFront>img,
      .tileBack {
        width: var(--tileWidth);
        height: var(--tileHeight);
      }
    

    Using CSS Variables to Morph Your SPFx Design at Run Time