How to add inline style in SPFx .tsx file

Scenario

You are developing a react SPFx web part and want to use a property pane value in style attribute. To use the property in tsx file, we can use inline styling. In this article, we will see how to use the inline style in our tsx file.

Quick answer

export default class GroupHeroWebPart extends React.Component < IGroupHeroWebPartProps, {} > {
  public render(): React.ReactElement<IGroupHeroWebPartProps> {
    let customStyle = {
      'background-image': `url(${this.props.backgroundUrl}`,
      width: '50%'
    };
    return(
      <div style={customStyle}>
        <p className={styles.description}>{escape(this.props.title)}</p>
        <p className={styles.description}>{escape(this.props.subtitle)}</p>
      </div >
    );
  }
}

Explanation

In the above code, I have created a variable named customStyle and stored all the CSS needed inline in the TSX file. If your style attribute has a hyphen in the name, like background-image, you have to use it in quotes. 

To use the style inline, just use the variable name as shown above in line number 8.

Post a Comment

0 Comments