Instant Component Creation in Atom

May 13th, 2016

Does your app have a ton of components? Are you tired of writing out class X extends React.Component... over and over again?

If you're using the Atom text editor, I've got a solution for you: snippets.

Check out this React component snippet in action. All I did is type 'comp', press return, and voila!

Add the React component snippet to Atom

If you like the component snippet I showed above, open up your snippets.cson file by typing this into your terminal:

atom ~/.atom/snippets.cson

Then paste this in there:

'.source.js':
  'react-component':
    'prefix': 'component'
    'body': """
import React from 'react';

class $1 extends React.Component {
  render() {
    return null;
  }
}
$1.propTypes = {
  $2
};
export default $1;
"""

<button class='copy-button' data-clipboard-action="copy" data-clipboard-target=".editor"

Copy to Clipboard

To test it just open up a new JavaScript file in Atom, type 'comp' and press return!

Make your own Atom snippet

If you like to save typing for all your repetitive tasks / boilerplate code, you can make more snippets. They all go in the snippets.cson file.

The snippets.cson file is in CoffeeScript-Object-Notation. Since CoffeeScript is like JavaScript shorthand, CSON is like JSON shorthand.

All you really need to know about CSON is that keys and values should be quoted with single quotes, there are no commas, indentation matters, and longer strings are wrapped in triple-quotes: """.

Your JavaScript snippets go in the .source.js section. Each snippet gets a prefix and a body:

  • prefix: What you type to trigger the snippet.
  • body: The text that appears when the snippet is triggered. Within the body you can add $1,$2, etc. in places where you want to manually fill in text within the snippet.

For example, here's the same snippets.cson file as above, but with another snippet added for mocha unit tests:

'.source.js':
  'react-component':
    'prefix': 'component'
    'body': """
import React from 'react';

class $1 extends React.Component {
  render() {
    return null;
  }
}
$1.propTypes = {
  $2
};
export default $1;
"""
  'mocha-test':
    'prefix': 'describe'
    'body': """
import { expect } from 'chai';

describe('$1', function() {
  it('should $2', function() {
    // test goes here
  });
});
"""

Now I just type describe to get all the boilerplate filled out for my next unit test!