Skip to main content

Adding Component Props

Defining Component Props

Just as in React, in FSComponent, components can take props that can be used to pass data or functions into them, making them more composable and able to take dependencies from their parent components. In order to define the props on a component, one must first make an interface that specifies what those properties will be. Let's define exactly what the text in our component should be via a prop, instead of hard-coding Hello World! into the component itself.

Making and Referencing the Props Interface

Above the MyComponent class, add the following interface definition:

interface MyComponentProps extends ComponentProps {
text: string;
}

and add ComponentProps to the import from @microsoft/msfs-sdk:

import { FSComponent, DisplayComponent, VNode, ComponentProps } from '@microsoft/msfs-sdk';

This will define a props interface that has a single property named text, which takes a string. We can then tell the system that we would like to use this set of props in our component by adding it to our class's extension of DisplayComponent, so:

export class MyComponent extends DisplayComponent<any> {

should become

export class MyComponent extends DisplayComponent<MyComponentProps> {

Utilizing the Props

All component props appear in this.props, just as they do in React. Therefore, we can now replace our Hello World! text in our component with a prop reference:

...
return (
<div class='my-component'>{this.props.text}</div>
);
...

Now, when the component is rendered, it will reference the value of that prop and replace this {} tag with the value.

Setting the Prop Value

You may notice that your editor is now complaining, adding a red underline in MyInstrument.tsx underneath MyComponent. This is because in our interface, we defined a mandatory prop text, but we have not yet provided a value for it. Let's do that now by changing that line and adding the prop:

FSComponent.render(<MyComponent text='Hello MSFS!' />, document.getElementById('InstrumentContent'));

You can see that we added text='Hello MSFS!' as a prop of the component. Props work a lot like HTML attibutes, and can be assigned values. After a rebuild/resync, you should see the text on your panel now reflect the prop value.