code-connect icon indicating copy to clipboard operation
code-connect copied to clipboard

Rendering `figma.string` inside a component.

Open rkieru opened this issue 1 year ago • 1 comments

  • Code Connect CLI version: 1.0.5
  • Operating system: macOS

Ask

I have a component in Figma that needs to output code similar to below:

<Component>
  <Icon>icon_name</Icon>
  Your text here
</Component>

But the <Icon /> component should only render if the hasIcon property in Figma is true and when it is I want it to pull in the icon property for the value. My attempt at this was:

figma.connect("...", {
  props: {
    icon: figma.boolean("hasIcon", {
      true: <Icon>{ figma.string("icon") }</Icon>,
      false: undefined,
    }),

    label: figma.string("label"),
  },

  example: ({ label, icon }) => {
    return (
      <Component>
        { icon }
        { label }
      </Component>
    )
  }
})

Of course this outputs the literal text <Icon>{ figma.string("icon") }</Icon> so my question is:

How do I capture the value of a figma string to insert it onto a conditional component, without the example return transforming into a more complex output? I would prefer to avoid the below, which does work:

figma.connect("...", {
  props: {
    icon: figma.boolean("hasIcon", {
      true: figma.string("icon"),
      false: undefined,
    }),

    label: figma.string("label"),
  },

  example: ({ label, icon }) => {
    const hasIcon = icon ? <Icon>{ icon }</Icon> : undefined;

    return (
      <Component>
        { hasIcon }
        { label }
      </Component>
    )
  }
})

But of course outputs a whole function for the rendering of a relatively simple component.

rkieru avatar Aug 16 '24 14:08 rkieru

Hi there! In this case as you've identified you won't be able to nest a figma.string call inside of a jsx component in the figma.boolean call. For now what you can do is use a variant restriction to define two versions of this component: I.e

figma.connect("...", {
  props: {
    icon: figma.string("icon"),
    label: figma.string("label"),
  },
  example: ({ label, icon }) => {
    return (
      <Component>
        { icon }
        { label }
      </Component>
    )
  }
})

figma.connect("...", {
  variant: { hasIcon: false }, // Use a variant to show this example when `hasIcon = false`
  props: {
    label: figma.string("label"),
  },
  example: ({ label, icon }) => {
    return (
      <Component>
        { label }
      </Component>
    )
  }
})

jyyang0 avatar Aug 19 '24 17:08 jyyang0