Reputation: 7114
To streamline adding a text input in a React component in VS Code, I have created a snippet that performs multiple transforms.
id
of the element to use hyphens (e.g. "user-name", as is normal for CSSname
of the element to use underscores, to match the field names in a database (e.g. "user_name")In many cases, I should be able to simply type the id
, and then press the TAB
key a few times to apply transforms to the various attribute values. However, I also want to be able to customize each value, so I have applied additional tab stops that allow me to edit the values for name
and onChange
.
Here's the working snippet:
"input:text": {
"prefix": "i:t",
"body": "<input\n type=\"text\"\n id=\"${1:user-name}\"\n name=\"${2:${1/-/_/g}}\" // ${4:${2/_(.)/${1:/upcase}/g}}\n onChange={${3:update${5:${4/(.*)/${1:/capitalize}/}}}}\n/>",
"description": "Text Input"
},
If you add this snippet to your javascriptreact.json
file, you can then type i:t
in a React script, then press TAB
a few times, to get this result**:
<input
type="text"
id="user-name"
name="user_name" // userName
onChange={updateUserName}
/>
I feel that I have had to cheat, though.
On the line for name
, you can see a comment: // userName
. To create my default listener name, I need to transform user_name
(with underscores) into UserName
(with a capital letter both at the beginning and to replace any letter after an underscore (that is, matching the regex /_(.)/
).
I haven't found a way of doing this in one step, so I have used an intermediary step ($4), which creates the commented string.
My question then: How could I alter the transforms used for the onChange
entry, so that I can avoid this intermediate step?
** You can, of course, type in your own values for id
, name
and the onChange
listener.
Upvotes: 0
Views: 45
Reputation: 7114
I have found an answer to my own question : )
/capitalize/
transform on the first character and the /camelCase/
transform on the rest."input:text": {
"prefix": "i:t",
"body": "<input\n type=\"text\"\n id=\"${1:user-name}\"\n name=\"${2:${1/-/_/g}}\"\n value={${3:$2}}\n onChange={${4:update${5:${2/(.)(.*)/${1:/upcase}${2:/camelcase}/}}}}\n/>",
"description": "Text input"
},
Here's where the answer comes from. Kudos to @Mark.
Upvotes: 0