13

I want to create VSCode snippet to quickly use React's useState. E.g. for a state open

const [open, setOpen] = useState()

I'm currently using

"const [ ${1}, set$1 ] = useState()"

But this gives me const [open, setopen] = useState(). Note the lack of caps on open.

I want to be able to just enter the state name open, and have the snippet sort out the capitalization for setOpen. I know I could use 2 variables, but I don't want to type it out twice since it'll always follow the pattern [foo, setFoo]

I know I can do transforms like ${1:/upcase}, but this capitalizes the entire variable, not just the first letter.

Henry
  • 165
  • 1
  • 6

1 Answers1

36

This should work:

"const [ ${1}, set${1/(.*)/${1:/capitalize}/} ] = useState()"
Guillermo Brachetta
  • 3,857
  • 3
  • 18
  • 36
  • 8
    Actually, this is enough for the `setOpen` term: `set${1/(.)/${1:/capitalize}/}` - you only need that first letter. – Mark Jan 22 '21 at 17:48
  • 19
    For everyone this didn't work for; remember that you need to press tab before the capitalisation is done :) – Jamie Robinson Oct 22 '21 at 13:39
  • 1
    And for anyone trying to use this as the 2nd variable, the first $1 is a variable reference, and the 2nd is a local regex reference, so it needs to look like this: `set${2/(.)/${1:/capitalize}/}` – sirclesam Nov 20 '22 at 13:33