How to modify component instance content?

Is it possible to use and modify component instance content via the plugin API?

I know I can create a component using createComponent() and after that I can create an instance of it using createInstance() but how can I modify it’s contents?

In my case I want to modify multiple TextNodes inside my component instances.
Is there any way of doing this?

Thank you in advance!

const instance = component.createInstance()
const text = instance.children[0] // if text is the first sublayer of instance
text.characters = "New Text" // do something with text

I dunno what’s the problem but all I get is an error

TS2339: Property 'fontName' does not exist on type 'SceneNode'.
Property 'fontName' does not exist on type 'SliceNode'.

My code goes like this

const myInstance = myComponent.createInstance()          
const text = myInstance.children[1]
text.fontName = { family: "Work Sans", style: "Regular" }
text.fontSize = 14
text.characters = "My text"

I do this with multiple nodes and all the fontName, fontSize and characters are highlighted with red underline in the editor with this same error.

See this answer: Get all nodes that are red - #4 by Gleb

1 Like

Okay, it’s New Years and it’s 3:30am here in Finland BUT I wanted to try this before I go to sleep :sweat_smile:

Thank you @Gleb :+1:

I got it working :fire:

1 Like

I checked the link you gave me and this is what I did:

// Function to check if node is a TextNode
function isText(node: SceneNode): node is TextNode {
  return node.type === "TEXT"

// Create instance of my component
const myInstance = myComponent.createInstance()

// Get the node I want - in my case it's the 2nd layer
const myTextNode = myInstance.children[1]

// Since I know that it's a TextNode I can use my simple function
if (isText(myTextNode)) {
  myTextNode.characters = "My text here"
1 Like

FYI this would throw an error if myTextNode is undefined (if instance has less than two children). You can check if it’s undefined via typeof myTextNode === "undefined"

Also now TypeScript has evolved and you don’t have to put the type condition into a function with type predicate, it should work as a normal type checking condition. Like this: if (myTextNode.type === 'TEXT') { }. However I still like the type predicate function more as you don’t have to write the same condition multiple times.

1 Like