Lightning Web Components – Fix ‘Cannot Read Properties of Undefined’ Error in FSC

flow-screen-componentjavascriptlightning-web-componentsvisual-flowsvisual-workflow

I'm building a LWC to be used as a flow screen component. In the LWC, I allow the border color of the component to be customised using a custom property. To set the color of the element, I'm using variables in my CSS file, and then updating them to the value of the color property in my LWC .js code. I was originally setting CSS variables like this:

document.body.style.setProperty('--MyFSC-borderColor', this.borderColor);

However, this affected all instances of the flow screen component on a screen.

I found a suggestion to use the following code instead, which scopes the function to only the to the individual component:

this.template.host.style.setProperty('--MyFSC-borderColor', this.borderColor);

This worked perfectly, until i added a section component to my flow screen, after which I started getting the error:
Something went wrong with the "MyFSC" screen component on the "MyFlow" flow. Contact your Salesforce admin about this error. Cannot read properties of undefined (reading 'setProperty')

Removing the section component from the screen resolves the error, however I would like to be able to scope my CSS variables to individual FSC instances, while also using sections. How can this be done?

Best Answer

The problem turned out to be with targeting this.template.host.style. I stopped doing this and instead used the querySelector() method scoped to this.template to select the element, and then used the setProperty() method on the element returned by this.

My updated JS looks like this:

const MyFSC_container = this.template.querySelector('.MyFSC_container');
MyFSC_container.style.setProperty('--MyFSC-borderColor', this.borderColor);