Building Figma’s Widget Code Generator

Rate this content

Widgets are custom, interactive objects you place in a Figma or Figjam file to extend functionality and make everything a bit more fun. They are written in a declarative style similar to React components, which gets translated to become a node on the canvas. So can you go the other way, from canvas to code? Yes! We’ll discuss how we used the public Figma plugin API to generate widget code from a design file, and make a working widget together using this.

19 min
24 Oct, 2022

Video Summary and Transcription

This Talk introduces Figma's Widget Code Generator and demonstrates how to build a FigJam widget using it. The speaker discusses the implementation of voting functionality, avatar functionality, and remove vote functionality. They also explain how the Widget Code Generator plugin works and how to access properties and modify names using the Figma plugin API.

Available in Español

1. Introduction to Figma's Widget Code Generator

Short description:

Hi, everyone. My name is Jenny, and I'm an engineer at Figma. In this talk, we'll be using Figma's widget Code Generator to build a FigJam widget and discuss its creation. FigJam is an online collaborative whiteboard tool where you can add widgets. To make FigJam files more flexible, there is a public widget API that allows you to write your own widgets. We'll start by designing a simple voting widget and writing the code for it. Then, we'll use the widget code generator plugin to generate the necessary components. By using these components, we can see our design come to life in FigJam. Let's dive in!

Hi, everyone. I hope you're having a lovely conference so far. My name is Jenny, and I'm an engineer at Figma. I'm based in Leeds, in the UK, so for those of you that didn't know Figma had a product team in Europe, now you know, and welcome to this talk on Figma's widget Code Generator. We're going to be using it to build a FigJam widget and then talk about how it was made.

On my screen now, you can see FigJam. This is Figma's online collaborative whiteboard tool where I can do things like add a post-it note, I can do some drawing, most importantly for this talk, I can add a widget. There we go. This can be seen and interacted with by everyone that is in the file, which at the moment is unfortunately just me. And they aren't just restricted to the existing widgets. So to make FigJam files as fun and as flexible as possible, there is a public widget API, a component-based API, quite similar to React, which allows you to write your own widgets. And that's what we're going to do now.

So I've got, if we go into Figma design, I've got my design for my widget here. It's just going to be a simple voting widget with a button here that you press to vote and that will increase the number of total votes so far and then put your little profile picture into a circle and line them up all along the bottom for however many times you voted. So, and then also I've got a code editor on the other side and this is the code for what my widget project looks like. Again, it's super simple. I'm going to write all of my code in code.tsx and I've got a package.json file with a couple of scripts. The one that we want is watch. So, if I run that now, npm run watch, it should start my widget running, put all its compiled code into code.js, and if I go back into FigJam, I can run my widget by going widgets, development, simple vote, and there we go, it says, hello, I am a widget, which is what the widget function is returning. And I can add some exclamation marks to this and they'll update in real time. So, hopefully this widget code is quite familiar to you. It looks just like React using JSX components and some specific Figma layout tags.

So, if we go back to our design, if we wanted to start coding this from scratch, we'd have to go through and look at our simple vote layout and see that it's a frame with auto layout set. So, we'd have to start adding an auto layout and then we'd have to look at the properties in that auto layout like the gap of four and put this in as spacing and you can see it would take quite a long time. So, earlier this year, I helped as part of our biannual maker week to create a widget code generator plugin and if we run that, this is available to everyone on Figma community, so if you just google Figma's widget code generator, this is something you can install yourself onto your Figma app. But if we run it here, and I'll just minimize this window, run it, and click on the thing that we want to get the code for, so our simple vote widget, you can see it generates all of these components for us, with a layout that looks pretty similar to the layout of the layers in Figma, and we can copy all of that and paste it into our text editor. It's complaining about avatar, so we'll just comment that out and come back to it in a minute. But what we've got is a function called Simple Vote. So if we take this Simple Vote component and then use it inside our main widget code, we'll go back to Big Jam, it's starting to look quite like our design already, isn't it? We've got the gradient, we've got the text, it's all laid out in the right place, but we're missing the pictures along the bottom, and that has probably got something to do with the thing that I just commented out.

2. Implementing the Voting Functionality

Short description:

If we use the Simple Vote component in our main widget code, it will start to resemble our design. However, we're missing the pictures along the bottom, which is related to the commented-out code. To resolve this, we need to go to the avatar component and include its code in our file. Once we do that, the widget will have the desired appearance. To make the button functional, we need to add an onclick event that updates the voters array and displays the user's picture. We achieve this by using the Figma widget API's you sync state to store the voters' state and the Figma.CurrentUser object to get the user's profile. Finally, we attach the onclick event to the VoteButton and update the displayed number using the voters.length property.

So if we take this Simple Vote component and then use it inside our main widget code, we'll go back to Big Jam, it's starting to look quite like our design already, isn't it? We've got the gradient, we've got the text, it's all laid out in the right place, but we're missing the pictures along the bottom, and that has probably got something to do with the thing that I just commented out.

So if we put it back, it's complaining that it cannot find avatar. And this is because in our design here, frames 6, 7 and 8, these are all instances of a component called avatar, and instead of doing this inline and just writing out the code three times, what we want you to do is go to the avatar component and get the code for that and put it into your file just like we did with simple vote. So now we've got a function for avatar, and these instances are a bit happier. And if we go back to FigJam again, if you've got really beady eyes, you'll be able to see that there are three faint white circles. That's because they're outlined in white. If we change the outline to red just so we can see where the circles are, there we've got it. We've basically got our widget. It doesn't do anything though. So we need to add an on click to this button. So when you click it, it will add you to the list of voters, increase that number and put your picture along the bottom.

Okay, so in simple vote, how we're going to do that is by storing some state of our voters. You probably recognize this from React. Instead of saying use state, we're going to say you sync state, which is part of the Figma widget API, give it a name and start it off as an empty array. Because this is a TypeScript file, I'm also going to give it a type that I know is going to be user. And then we want to update this voters array when someone clicks on the button. I'm going to make an onclick function. And when they click, we want to get your profile as the person who's voted, because that's going to let us get your profile photo. And to do that, we can say voter is Figma.CurrentUser. And Figma here is a global object that is provided in the widget run time that lets us get things like the current user and loads of other information about what's going on in the file. So now we've got this voter. I know that this voter can sometimes be null. It probably won't be, but just to protect against that, I'm going to say if we don't have a photo, voter, don't do anything. And if we do have a voter, we're going to set voters, get our original list, and add a new voter to the list. And our OnClick is useless if we don't put it anywhere. So we want it to happen when we click on this button, which we can find in the layout because it's called VoteButton. And all of these tags can have an OnClick attached to them. So I'm going to put that OnClick on there. And then we also need to use the voters array to update the number here. So previously where it's had three hard coded, instead, we're going to use voters.length.

3. Implementing Avatar Functionality

Short description:

The avatars along the bottom are still hard coded. We want to map through our voters and return an avatar for each one. The avatars need to get a photo from a user profile, so we pass the photo URL as the source. We no longer need the red border and can go back to a stylish white. We can add more functionality, such as an onclick event to remove a voter by using a remove function.

So it's gone back to zero, which is good. And if we click on this button, it will increase every time we click. Nice. But the avatars along the bottom are still staying as three. That's because they're still hard coded here. So instead of this hard coding, what we want to do is map through our voters. And each time we get a voter, we want to return an avatar.

Now we've got three. When we click it, we've got four, five. And as well on these avatars, they need to get a photo from a user profile. So I'm going to pass it to this. We're going to say it's going to take in a photo URL, but a photo URL. Again, this could be undefined. So just to keep TypeScript happy, let's set this to an empty string avatar at the moment. Doesn't take in photo URL. But because it is just a function that we've copy pasted from the code generator that takes in props. I'm going to extend these props and say it takes in a photo URL, which is a string in the design on this component, we can see that it's got an image fill here, which is my very nice little stickman drawing. And this image fill translates to here in the properties and it expects a URL as the source. So we can just pass that props photo URL in as the source. And there I am. And we no longer need the horrible red border. We can go back to a stylish white. And if I keep voting, there's more and more and more of me. And we've got a working widget. We can add loads more to it if we want.

So, for example, like I said before, our avatar component because it takes in props of the type of its top level frame. In this case, which is just a frame, we could add an on click to this avatar. So when we click on it, I'm removed from the voters. I actually made a remove function earlier. So you wouldn't have to painfully watch me go through how to do a splice on an array.

4. Implementing Remove Vote and Widget Code Generator

Short description:

If I add the remove vote functionality, we can remove votes by clicking on the avatars. The widget code generator is a Figma plugin that uses the public Figma plugin API. It can read from and write to a Figma file, and provides access to the Figma global object. In the Figma Electron app console, we can use the Figma object to create and inspect objects in the file.

If I add this remove vote here, we don't even need to add an extra prop to avatar. We can just pass it straight in as an on click. If I spell it right, it should remove the vote. It does need to take in an index because it's removing something at a certain index of the array. So we'll just have to update our map to also pass along the index. And now it doesn't happen straight. When I click on my avatar, it will delete me. So if I accidentally vote too many times, I can remove some votes again. Nice.

And I promised at the start that we'd go through a bit how this widget code generator works. It is written as a Figma plugin, so it's running in an iframe, in a sandbox, with a runtime, a JavaScripty runtime given to it by Figma. And similarly to the widgets, this is using the public Figma plugin API. So there's a whole website full of API reference and everything you'd want here. It's all documented and just waiting for you to build your own plugins with it. It can both read from and write to a Figma file. And like the widgets, it uses this Figma global object that's provided at runtime for you to access everything on the file. But we're not going to go through all of this API documentation together. You can do that in your own time if you want.

What I'm going to show you is something fun that if we open the console in the Figma Electron app and get rid of all of the information, it says at the moment. What we can do is type Figma and get access to this global Figma object here. We've got loads of stuff. We've got metadata like the active users, that will be me. We've got functions to create things. We've got functions to access all the styles in a file, all the components, all the images. The world is your oyster really. If we use one of them, we can say Figma create rectangle and it's created a rectangle in our file. We can say Figma create ellipse, it's created an ellipse. And then we can also inspect these things in the file. So if we select this and then say Figma current page selection 0, this is one I've done before. Selection is an array.

5. Accessing Properties and Modifying Names

Short description:

We can access all the properties of the Figma graphical user interface, such as auto layout, spacing, width, fill, and children, through the plugin API. By inspecting the children, we can navigate through different nodes and understand the relationship between the plugin API and the generated widget code. The plugin API provides us with the necessary properties, which we modify to align with React conventions. We remove defaults, map them to the appropriate tags, and incorporate an HTML front-end to create the plugin.

So we just want to access the first thing. We can inspect all of this. So anything that you can access in the Figma graphical user interface, like the auto layout information, the spacing, the width, the fill, the children, we can get all of that via the plugin API. So if we go into children, we can see it's got the frame node, the rectangle node, and another frame node and drill down right to the bottom in there. And you are probably starting to join the dots here between the information given to us by this plugin API and the generated widget code. It really is that simple, that basically we have taken the properties given to us by the plugin API. We've changed some of the names to make them a bit more React-like. So, for example, clips-content false has been converted to overflow somewhere. Yeah, overflow visible, clips-content false. We've got rid of any defaults, mapped them to use the correct tag. So if it's a frame using Auto-layout, we've mapped it to Auto-layout. And then added a HTML front-end and created a plugin.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

JSNation 2023JSNation 2023
29 min
Modern Web Debugging
Few developers enjoy debugging, and debugging can be complex for modern web apps because of the multiple frameworks, languages, and libraries used. But, developer tools have come a long way in making the process easier. In this talk, Jecelyn will dig into the modern state of debugging, improvements in DevTools, and how you can use them to reliably debug your apps.
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
TechLead Conference 2023TechLead Conference 2023
35 min
A Framework for Managing Technical Debt
Let’s face it: technical debt is inevitable and rewriting your code every 6 months is not an option. Refactoring is a complex topic that doesn't have a one-size-fits-all solution. Frontend applications are particularly sensitive because of frequent requirements and user flows changes. New abstractions, updated patterns and cleaning up those old functions - it all sounds great on paper, but it often fails in practice: todos accumulate, tickets end up rotting in the backlog and legacy code crops up in every corner of your codebase. So a process of continuous refactoring is the only weapon you have against tech debt.In the past three years, I’ve been exploring different strategies and processes for refactoring code. In this talk I will describe the key components of a framework for tackling refactoring and I will share some of the learnings accumulated along the way. Hopefully, this will help you in your quest of improving the code quality of your codebases.

React Summit 2023React Summit 2023
24 min
Debugging JS
As developers, we spend much of our time debugging apps - often code we didn't even write. Sadly, few developers have ever been taught how to approach debugging - it's something most of us learn through painful experience.  The good news is you _can_ learn how to debug effectively, and there's several key techniques and tools you can use for debugging JS and React apps.
React Advanced Conference 2022React Advanced Conference 2022
22 min
Monolith to Micro-Frontends
Top Content
Many companies worldwide are considering adopting Micro-Frontends to improve business agility and scale, however, there are many unknowns when it comes to what the migration path looks like in practice. In this talk, I will discuss the steps required to successfully migrate a monolithic React Application into a more modular decoupled frontend architecture.

Workshops on related topic

React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
React Summit Remote Edition 2021React Summit Remote Edition 2021
87 min
Building a Shopify App with React & Node
Top Content
Shopify merchants have a diverse set of needs, and developers have a unique opportunity to meet those needs building apps. Building an app can be tough work but Shopify has created a set of tools and resources to help you build out a seamless app experience as quickly as possible. Get hands on experience building an embedded Shopify app using the Shopify App CLI, Polaris and Shopify App Bridge.We’ll show you how to create an app that accesses information from a development store and can run in your local environment.
JSNation 2022JSNation 2022
41 min
Build a chat room with Appwrite and React
API's/Backends are difficult and we need websockets. You will be using VS Code as your editor, Parcel.js, Chakra-ui, React, React Icons, and Appwrite. By the end of this workshop, you will have the knowledge to build a real-time app using Appwrite and zero API development. Follow along and you'll have an awesome chat app to show off!
GraphQL Galaxy 2021GraphQL Galaxy 2021
164 min
Hard GraphQL Problems at Shopify
At Shopify scale, we solve some pretty hard problems. In this workshop, five different speakers will outline some of the challenges we’ve faced, and how we’ve overcome them.

Table of contents:
1 - The infamous "N+1" problem: Jonathan Baker - Let's talk about what it is, why it is a problem, and how Shopify handles it at scale across several GraphQL APIs.
2 - Contextualizing GraphQL APIs: Alex Ackerman - How and why we decided to use directives. I’ll share what directives are, which directives are available out of the box, and how to create custom directives.
3 - Faster GraphQL queries for mobile clients: Theo Ben Hassen - As your mobile app grows, so will your GraphQL queries. In this talk, I will go over diverse strategies to make your queries faster and more effective.
4 - Building tomorrow’s product today: Greg MacWilliam - How Shopify adopts future features in today’s code.
5 - Managing large APIs effectively: Rebecca Friedman - We have thousands of developers at Shopify. Let’s take a look at how we’re ensuring the quality and consistency of our GraphQL APIs with so many contributors.
JSNation 2023JSNation 2023
57 min
0 To Auth In An Hour For Your JavaScript App
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.js backend + Vanilla JS frontend) to authenticate users with One Time Passwords (email) and OAuth, including:
- User authentication – Managing user interactions, returning session / refresh JWTs- Session management and validation – Storing the session securely for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.