Adding boilerplate code of React component in SPFx using VS Code

React does not provide command line interface like Angular’s ng generate to create boilerplate code for React components. So you end up copying code from previous components and then modifying it. VS Code has snippets feature that we can leverage to create our own boilerplate code.

To create your own snippets, go to User Snippets under File > Preferences (Code > Preferences on macOS) and select New Global Snippets file… Enter the name of the snippet file. You get a JSON file with below contents.

{
	// Place your global snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and 
	// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope 
	// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is 
	// used to trigger the snippet and the body will be expanded and inserted. Possible variables are: 
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. 
	// Placeholders with the same ids are connected.
	// Example:
	// "Print to console": {
	// 	"scope": "javascript,typescript",
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }
}

Update the file with below code.

{
	"SPFx React Component Template": {
		"prefix": "spfxtsx",
		"body": [
			"import * as React from 'react';" ,
			"export default class $1 extends React.Component<I$1Props, {}> {" ,
			"    constructor(props: I$1Props, public state: any) {" ,
			"        super(props);" ,
			"    }" ,
			"    public componentDidMount() {" ,
			"    }" ,
			"    public render(): React.ReactElement<I$1Props> {" ,
			"        return(<>" ,
			"        </>);" ,
			"    }" ,
			"}" ,
			"interface I$1Props {}"
		],
		"description": "Creates React component boilerplate code for SPFx"
	}
}

The prefix (spfxtsx) here is the trigger text which will give you option to enter the snippet. $1 indicates tabstop and allows user to enter the name of the component, which is also used in name of props interface. In your tsx file when you start entering spfxtsx, it will populate with boilerplate code.