MSBA-271 · Lesson 6 of 12 · 19 min
Building a code component
▶ Video coming soon A video version of this lesson is on the way.
Before building RoomPicker, Signe wanted Wiremu to build something small from start to finish, so that the floor plan would not be his first contact with manifests and builds. Octavia Brenner-Lau had asked for a simple control on the Room form: a bar showing how many people a room is booked for against its capacity, turning amber at 90 percent and red at capacity. It needed two numbers, drew one shape and wrote nothing back. It was perfect for learning.
Tools and setup
Code components are built on a developer's machine and pushed to an environment. The tools are the same ones introduced in MSBA-270: Node.js (a long-term support version) and npm for building, Visual Studio Code for editing, and the Power Platform CLI (pac) for creating projects and pushing components. The .NET SDK is needed later, when the component is packaged into a solution project. Wiremu already had Node.js and Visual Studio Code. He installed the Power Platform CLI through the Power Platform Tools extension for Visual Studio Code and signed in to Wiremu Dev with pac auth create.
Creating the project
A new project comes from pac pcf init, which takes a namespace, a name and a template, and optionally the framework and whether to run npm install straight away.
mkdir RoomCapacity
cd RoomCapacity
pac pcf init --namespace Lumenvale --name RoomCapacity --template field --framework react --run-npm-installThe command creates a folder of files that every code component shares. Wiremu spent ten minutes reading each one before changing anything, which Signe said was ten minutes well spent.
The manifest
The manifest, ControlManifest.Input.xml, describes the component to the platform: its name and namespace, its version, its type, the properties makers can bind or set, the resources it loads and the features it uses. Makers never see the TypeScript, but they see everything in the manifest through the designer, so it deserves care.
<?xml version="1.0" encoding="utf-8" ?>
<manifest>
<control namespace="Lumenvale" constructor="RoomCapacity" version="1.0.3"
display-name-key="RoomCapacity_Display" description-key="RoomCapacity_Desc"
control-type="virtual">
<property name="booked" display-name-key="Booked_Display" description-key="Booked_Desc"
of-type="Whole.None" usage="bound" required="true" />
<property name="capacity" display-name-key="Capacity_Display" description-key="Capacity_Desc"
of-type="Whole.None" usage="input" required="true" />
<property name="warnAt" display-name-key="WarnAt_Display" description-key="WarnAt_Desc"
of-type="Whole.None" usage="input" required="false" default-value="90" />
<resources>
<code path="index.ts" order="1" />
<platform-library name="React" version="16.14.0" />
<platform-library name="Fluent" version="9.46.2" />
<css path="css/RoomCapacity.css" order="1" />
<resx path="strings/RoomCapacity.1033.resx" version="1.0.0" />
</resources>
</control>
</manifest>| Manifest element or attribute | Purpose |
|---|---|
| control: namespace, constructor, version | Identify the component; the version must increase for updates to be picked up |
| control-type | standard or virtual (React); cannot be changed to convert an existing component |
| property: usage="bound" | Bound to a column; the component can read and write it |
| property: usage="input" | A value set by the maker or another column, read only for the component |
| property: usage="output" | A value the component produces for canvas apps to read |
| of-type and type-group | The data type of a property, or a group of types it accepts |
| resources: code, css, resx, img, platform-library | Files and shared libraries the component loads |
| feature-usage and uses-feature | Host features the component needs, such as WebAPI |
Property usage is the detail most often tested and most often misunderstood. A bound property is connected to a column: the component reads its value and can write a new one through getOutputs. An input property is a value the maker sets in the designer or binds to another column, which the component only reads. An output property, used in canvas apps, exposes a value the app can read from the control. In RoomCapacity, booked was bound so the control could later allow editing, capacity was an input bound to the room's capacity column, and warnAt was a static input with a default of 90.
A type-group lets a property accept several types, for example any whole or decimal number, so that makers can bind the control to more columns. Wiremu defined one for numbers, which meant Octavia could later reuse the control for parking spaces, which were stored as decimals.
The TypeScript
The template's index.ts already has the four lifecycle methods. For a React component, updateView returns a React element built from a small function component, which keeps rendering logic separate from the lifecycle plumbing.
import { IInputs, IOutputs } from "./generated/ManifestTypes";
import * as React from "react";
import { CapacityBar } from "./CapacityBar";
export class RoomCapacity implements ComponentFramework.ReactControl<IInputs, IOutputs> {
private notifyOutputChanged!: () => void;
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void): void {
this.notifyOutputChanged = notifyOutputChanged;
}
public updateView(context: ComponentFramework.Context<IInputs>): React.ReactElement {
const booked = context.parameters.booked.raw ?? 0;
const capacity = context.parameters.capacity.raw ?? 0;
const warnAt = context.parameters.warnAt.raw ?? 90;
return React.createElement(CapacityBar, {
booked, capacity, warnAt,
disabled: context.mode.isControlDisabled,
label: context.resources.getString("Bar_Label")
});
}
public getOutputs(): IOutputs {
return {};
}
public destroy(): void { }
}Three details deserve attention. The generated ManifestTypes file gives TypeScript types for the properties, so a typo in a property name is a build error rather than a run-time surprise; it is regenerated by the build whenever the manifest changes. raw is the property's underlying value, which can be null when the column is empty, hence the defaults. And the label comes from the resx file through context.resources, so the text can be translated and changed without touching code.
The CapacityBar function component was ordinary React: a Fluent ProgressBar, a text label stating "18 of 20 booked", and a color that depended on the percentage. Wiremu kept the color logic and the text together so that the meaning never depended on color alone, a point lesson 10 returns to.
Writing values back
RoomCapacity only displayed values. Most useful controls also change them, and the pattern is always the same: hold the new value, call notifyOutputChanged, and return it from getOutputs.
private currentValue: number | null = null;
private onUserChange = (value: number | null): void => {
this.currentValue = value;
this.notifyOutputChanged(); // ask the host to call getOutputs
};
public getOutputs(): IOutputs {
return { booked: this.currentValue ?? undefined };
}Returning undefined for a property means "no change". Returning null clears the column. Confusing the two is a classic way to wipe data, and Wiremu wrote a unit test for it in the next session.
Building and running locally
npm scripts in package.json wrap the build. npm run build compiles the TypeScript, checks the manifest and bundles the output into the out folder. npm start watch builds, starts the test harness in a browser and rebuilds whenever a file changes. The test harness hosts the component outside any app, with a panel for setting property values, the form factor and the available size, so a developer can exercise the control without deploying it.
npm run build
npm start watchThe test harness has limits. It does not provide real Dataverse data, so context.webAPI and some other services behave differently or not at all, and it is not the real form, so business rules and other scripts do not run. It is for the control's own behavior: drawing at different sizes, handling empty values, responding to disabled mode. Wiremu typed 0, null, 19, 20 and 25 into the booked field and watched the bar change, and found that a capacity of 0 caused a division by zero. He fixed it to show "Capacity not set" instead.
Styling and resources
CSS for a component goes in a file listed in the manifest. Because the component shares the page with everything else, its styles must be scoped to the component's own root element or class names, never to bare element names that would restyle the whole form. React components using Fluent get the app's look by default, which is usually the best styling decision. Images and strings are resources too: img elements in the manifest for icons, resx files for text, one per language with the language code in the name, such as 1033 for English (United States) and 1036 for French. Lumenvale, a Canadian college system, planned to add a French file later for bilingual programs.
Worked problem
Designing the properties for a component
Delphine asks for a control on the work order form that shows the due date as a countdown, such as "Due in 3 days", turns red when overdue, and lets the dispatcher pick a new date by clicking. Makers should be able to choose how many days count as "soon". Define the properties.
Show solution
- The due date itself is read and written by the control, so it is a bound property of type DateAndTime.DateOnly or DateAndTime.DateAndTime, matching the column.
- The number of days that counts as soon is set by the maker and only read by the control, so it is an input property of type Whole.None with a default, for example 3.
- If the control should also work in a canvas app where the screen needs to know whether the job is overdue, an output property such as isOverdue of type TwoOptions can expose it.
Answer: One bound date property, one input whole number with a default, and optionally an output for canvas apps. The manifest, not the code, is where makers see these choices.
Responding to size and form factor
A component should draw well at every size it is given. In the init method, calling context.mode.trackContainerResize(true) asks the host to report the space allocated to the component, and updateView then receives context.mode.allocatedWidth and allocatedHeight. A value of minus one means the host has not set that dimension. RoomCapacity used the width to choose between a full bar with text beside it and a compact layout with the text below, so that it worked in a narrow form column on a phone as well as a wide one on a desktop.
public updateView(context: ComponentFramework.Context<IInputs>): React.ReactElement {
const width = context.mode.allocatedWidth;
const compact = width > 0 && width < 320;
return React.createElement(CapacityBar, {
booked: context.parameters.booked.raw ?? 0,
capacity: context.parameters.capacity.raw ?? 0,
compact,
disabled: context.mode.isControlDisabled,
});
}The client also reports the form factor through context.client.getFormFactor, which distinguishes desktop, tablet and phone. Signe preferred width to form factor for layout decisions, because a desktop browser can be narrow and a tablet can be wide; form factor is better for behavior that depends on the device, such as larger touch targets.
Respecting state: disabled, secured and loading
Three kinds of state are easy to forget. When the form is read-only, or the column is locked, context.mode.isControlDisabled is true, and the component must not allow changes; a disabled component that still accepts input will lose those changes, or worse, save them through another route. When column-level security applies, the bound property carries security information saying whether the user can read and edit the column, and the component should show a masked or read-only state accordingly. And while data is still arriving, properties can report that they are loading; drawing an empty or zero state during loading makes the control flicker, so RoomCapacity showed a quiet placeholder instead.
Keeping updateView fast
The host calls updateView often: when any bound or input property changes, when the container resizes, and at other times the host decides. Anything slow in updateView makes the whole form feel slow. Wiremu followed three rules. Do not call the Web API on every update; fetch data when the relevant input actually changes, and cache the result. Do not rebuild expensive objects each time; in React components, keep props simple and let React skip work when nothing has changed. And check context.updatedProperties when it helps, since it lists what changed since the last call, so a resize need not trigger a data reload.
| Situation | What RoomCapacity did |
|---|---|
| Form is read-only | Drew the bar without any interactive elements |
| User cannot read the column | Showed a masked value rather than zero |
| Values still loading | Showed a placeholder instead of an empty bar |
| Container resized | Switched layout without fetching data again |
Wiremu tested each of these states deliberately in the harness before pushing the component anywhere. He set the form to read-only, cleared the capacity input, entered a booked value larger than the capacity and shrank the container to the width of a phone column, and he wrote down what the control showed in each case. Two of the cases surprised him: an overbooked room drew a bar wider than its container, and a capacity of zero divided by zero. Both became unit tests in lesson 7, and both fixes were a single line. Signe's comment was that the harness is where a component meets its awkward cases cheaply, and that every awkward case found there is one a dispatcher will never see on a busy morning.
Common mistakes
MistakeForgetting to increase the manifest version.
InsteadIncrease it with every change; the platform may keep using the old version otherwise.
MistakeMarking a property bound when the control only reads it.
InsteadUse input for values the control only reads.
MistakeReturning null from getOutputs to mean "no change".
InsteadReturn undefined for no change; null clears the column.
MistakeStyling bare elements such as div or button in the component CSS.
InsteadScope styles to the component's own class names.
MistakeHard-coding display text in TypeScript.
InsteadPut text in resx files so it can be translated and changed.
By the end of the session RoomCapacity worked in the test harness at three sizes and with empty values. Wiremu asked how to get it onto Octavia's form. "That," said Signe, "is where most component projects go wrong, so it gets its own session."
Summary and key terms
- pac pcf init creates a project from a namespace, name, template (field or dataset) and optional framework (react).
- The manifest declares the control type, properties with usage bound, input or output, types or type-groups, resources and features; increase its version with every change.
- index.ts implements the lifecycle using generated types; React components return elements from updateView.
- Write values back by storing them, calling notifyOutputChanged and returning them from getOutputs; undefined means no change and null clears.
- npm run build compiles; npm start watch opens the test harness, which tests the control's own behavior without real data or form logic.
- Manifest
- ControlManifest.Input.xml, which describes a code component's properties, resources and features.
- Bound property
- A property connected to a column that the component can read and write.
- Input property
- A property the component reads but does not write.
- Type-group
- A named set of data types a property can accept.
- Test harness
- A local browser page that hosts a code component for testing outside an app.
- resx file
- A resource file holding display strings for one language.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which command creates a dataset component project using React?
Show answer
pac pcf init with --template dataset and --framework react, plus a namespace and name.
What is the difference between a bound and an input property?
Show answer
A bound property is connected to a column the component can write through getOutputs; an input property is only read.
What can the test harness not show you?
Show answer
Real Dataverse data and services, and the behavior of the real form, such as business rules and other scripts.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.