Scenario
When we add an SPFx webpart on a page, it should bring the current site title from the property pane and render it on UI.
Quick answer
We can get the current site title using below syntax
this.context.pageContext.web.title
We know that we can set default values of the property using manifest.json file
In this case, we cannot use the manifest.json file as we will not get the pageContext.
We can use the alternative as below:
We can use the alternative as below:
- Add a new property called siteTitle as shown below
public render(): void { const element: React.ReactElement<IGroupHeroWebPartProps> = React.createElement( GroupHeroWebPart, { title: this.properties.title, subtitle: this.properties.subtitle, backgroundUrl: this.properties.backgroundUrl, siteTitle: this.context.pageContext.web.title } ); ReactDom.render(element, this.domElement); }
- Add current site title in property pane dynamically as below
protected onPropertyPaneConfigurationStart(): void { if(!this.properties.title){ this.properties.title = this.context.pageContext.web.title; this.context.propertyPane.refresh(); } }
- In your .tsx file, use the title property. here we are checking if the Title property is blank, we are appending the Site title directly, else we are fetching the value from property pane.
<div> <p className={styles.description}>{this.props.title ? escape(this.props.title) : this.props.siteTitle}</p> <p className={styles.description}>{escape(this.props.subtitle)}</p> </div >
0 Comments