VS Code — how to create snippets to speed up your React Native development

Mike Callahan
React Native Institute
3 min readJan 22, 2017

After going through a couple tutorials and trying a few things on my own, I quickly realized there’s a lot of code repetition when creating react native apps. The majority of components I write all have the same 4 sections.

1. importing libraries
2. creating the component
3. defining styles
4. making the component available to the app

After writing the same basic code and structure over and over again, I decided to figure out how to create snippets that can “pop” the basic code in with just a couple keystrokes. Visual Studio Code has an easy way to do this with “snippets”.

To open up your snippets file, go to Code > Preferences > User Snippets (File > Presferences > User Snippets on Windows) and select “JavaScript” (not JavaScript React). If you don’t have any snippets yet and you just have comments, you can delete the contents and paste the following:

Note line 3: “prefix” : “cc”,

Once saved, open a new file called test.js. On line 1 begin typing “cc” and you will notice your new custom snippet selected in the popup.

Hit <return> and the component template will pop in to your test.js file. You’ll notice your cursor is on line 6 with filename highlighted, this is referred to as a placeholder.

Type the name of your file, in this case test. Placeholders are defined in your snippet code like this: ${1:foo}. If your snippet contains multiple placeholders you can move between them using the <tab> key.

I use three snippets routinely. I have one for functional components, one for class components and one for the IOS and android index files (index.ios.js and index.android.js). If you want to use them you can copy the code below:

I like to set the index files to exactly the same code and then drive my application through App.js which I store in a folder I name src. Open index.ios.js, remove all the code (command-A <delete>) then pull in the snippet by typing index and hitting <return> with your index snippet highlighted. Change projectname to the name of your project.

Repeat for index.android.js. Now create the src folder and App.js file, type cc <return> in your App.js file to pull in the class component snippet and you’re good to go.

To learn more about snippets, check out the VS Code documentation here: https://code.visualstudio.com/Docs/customization/userdefinedsnippets.

There’s a lot you can do with snippets to speed up your development, hopefully this gives you an idea of what’s possible.

--

--

Mike Callahan
React Native Institute

Building stuff on the web and mobile devices and sharing with others.