Home > other >  How to add custom code snippet with argument in prefix [VS CODE]
How to add custom code snippet with argument in prefix [VS CODE]

Time:08-15

For example, i am using React, and i tired to write every time full line:
const [state, setState] = React.useState("start value")
I wanna shortcut this to usestate state where usestate is the command and state is parameter.
More examples: usestate isLoading -> const [isLoading, setIsLoading] = React.useState($0)
How to rich it?

CodePudding user response:

If you want to be able to type something like usestate isLoading and have it automatically expand to your desired output, then react setstate with hypersnips demo

Note the trigger (usestate)\s ([^ ] ) has a space at the end! That is necessary since the regex is looking for non-space characters for the state and it will know that by the first space character.

[Right now, the tabstop $0 or $1 aren't working for me...]


There are a number of other ways to approach this. The simplest is probably to just make a snippet like the following (in one of your snippets files):

"React setState": {
  "prefix": "usestate",
  "body": [
    // "const [${TM_SELECTED_TEXT/^.*\\s (.)(.*)$/$1$2, set${1:/upcase}$2/}] = React.useState($0)"
    "const [$1, ${1/(.)(.*)/set${1:/upcase}$2/}] = React.useState($0)"
  ]
}

react setState demo

Here you type the prefix usestate, choose that snippet from the suggestions and then type isLoading, Tab and then snippet completes.

It isn't the workflow you asked for but it is simpler than getting something like HyperSnips up and running.


Another approach if you really want to type usestate isLoading and then trigger completion is to use a macro extension like React setstate keybinding demo

  • Related