How to: Adding a property to client-side web part

In this small walkthrough we will learn how to add property to client-side web part created using default template in SharePoint Framework (SPFx). Starting point is a web part which does not use any framework, but pure JavaScript, as we would get by following first tutorial for SPFx web part https://dev.office.com/sharepoint/docs/spfx/web-parts/get-started/build-a-hello-world-web-part.

After you create web part and add it to page, you will notice that there is only one property in property pane that we get when we edit web part. The property has name Description and it is string:

image

Let’s go a step further and make a title (Welcome to SharePoint) configurable. I will use code and all its feature “Go To Definition” to make this process as easy as possible.

In our Web Part class HelloWorldWebPart.ts which is in folder src/weparts/helloWorld we can se that Description property is used inside render() method as

${escape(this.properties.description)}

Using Go To Definition on decription we can see that this property is defined in IHelloWorldWebPartProps interface. Let’s add another property called pageTitle here:

image

Now we can use our new property in render() method like this

image

At this moment, even though we did create our property, it is not customizable in property pane – we don’t see it there if we edit web part.

To add the property in property pane, we can add it to groups area in method getPropertyPaneConfiguration:

image

We also need to customize the label for the textbox control in property pane. To do this, we can either hardcode the value or add new string property to our interface for custom strings that is already part of the project. As the hardcoding values is never recommended, we will add new string property PageTitleFieldLabel to our strings definition interface in file mystrings.d.ts in loc subfolder

image

We will now assign the value for PageTitleFieldLabel in file en-us.js that is stored in same folder. This file contains values for all custom strings for specific language, in this case English(US). If we would like to add more languages to our project, we could do it by adding values in specified language to file named -.js to this folder, for example de-de.js

image

Our web part property pane now looks like this, with new property which we can edit and customize.

image

Finally, to set a default value for this web part, we can add it to web part manifest *HelloWorldWebPart.manifest.json – we do that in properties collection

image

When we stop our test server and start it again, we will see that these default values are visible on the web part properties and in the web part immediately after we add it to the page

image

To learn more about custom properties, visit section Configure the Web part property pane in the tutorial https://dev.office.com/sharepoint/docs/spfx/web-parts/get-started/build-a-hello-world-web-part#web-part-project-structure