Abhishek Konnur
Abhishek Konnur

Reputation: 529

How to import a component from published library and how to get component key

I'm working on a figma plugin where in I need to use the components which are in published library assets. I know I should be using figma.importComponentByKeyAsync() of figma plugin API, but I m not sure from where will I get the component key. Can anyone guide on how to get component keys for each component

Upvotes: -1

Views: 37

Answers (1)

tank666
tank666

Reputation: 1

You can get component keys from a library in different ways.

For example, using the Plugin API: open the library file and find all the main components, for example, using the findAllWithCriteria method.

let components = figma.root.findAllWithCriteria({types: ['COMPONENT']}),
    componentKeys = components.map(v => v.key);
console.log(componentKeys);

Or the REST API: using the GET team components or GET file components endpoints.

// Example of using the 'GET file components' endpoint
let token = 'YOUR_PERSONAL_ACCESS_TOKEN',
    fileKey = 'YOUR_LIBRARY_FILE_KEY',
    api = `https://api.figma.com/v1/files/${fileKey}/components`;

fetch(api, {headers: {'X-FIGMA-TOKEN': token}})
    .then(response => {
        if (response.ok) return response.json();
    })
    .then(data => {
        console.log(data.meta.components.map(v => v.key));
    });

Please note: to use the REST API, you will need to use or generate a new personal access token, and know the team or file IDs.

Once you have obtained the required component keys, you can import the components into the file you need using the importComponentByKeyAsync method.

Upvotes: 0

Related Questions