178 words
1 minute
A Handy React Code Snippet for VSCode

In React projects you’re constantly creating new components and pages, and a good snippet can scaffold the boilerplate for you in a second.

The usual ritual: create a folder, add an index.tsx inside it, and write the component there. By convention the component is named after the folder — but VSCode doesn’t expose a variable for the current folder’s name, only its full path, so you need a regex to extract the name from the path.

That’s exactly what this snippet does.

First, create a new user snippet: open the command palette (cmd + shift + p), run “Preferences: Configure User Snippets”, and pick “New Global Snippets file…”.

If you’re using typescript, paste this in:

{
"React Functional Component": {
"prefix": "rfc",
"body": [
"const ${1:${TM_DIRECTORY/^.+\\/(.*)$/$1/}}: React.FC = () => {",
" return (",
" <div>$1</div>",
" );",
"};",
"",
"export default $1;"
],
"description": "Create a React functional component with folder name"
}
}

If you’re on plain javascript, just drop the : React.FC from the first line of body.

To use it, type rfc and hit tab — the template fills itself in.

A Handy React Code Snippet for VSCode
https://www.mihouo.com/en/posts/front/a-handy-react-code-snippet-in-vscode/
Author
Jia
Published at
2024-08-06
License
CC BY-NC-SA 4.0