Code Monkey home page Code Monkey logo

simple-react-snippets's Introduction

Simple React Snippets

The essential collection of React Snippets and commands.

snippets in action

Features

Only what you need and nothing more. No Redux. No React Native.

Simply, simple React snippets.

These snippets were selected carefully from my own day-to-day React use. Not everything in React is included here. This is a hand selected set of snippets that work the way that you would expect, not just a copy of the documentation.

Snippets

Snippet Renders
imr Import React
imrc Import React / Component
imrd Import ReactDOM
imrs Import React / useState
imrse Import React / useState useEffect
impt Import PropTypes
impc Import React / PureComponent
cc Class Component
ccc Class Component With Constructor
cpc Class Pure Component
ffc Function Component
sfc Stateless Function Component (Arrow function)
cdm componentDidMount
uef useEffect Hook
ucb useCallback Hook
cwm componentWillMount
cwrp componentWillReceiveProps
gds getDerivedStateFromProps
scu shouldComponentUpdate
cwu componentWillUpdate
cdu componentDidUpdate
cwun componentWillUnmount
cdc componentDidCatch
gsbu getSnapshotBeforeUpdate
ss setState
ssf Functional setState
usf Declare a new state variable using State Hook
ren render
rprop Render Prop
hoc Higher Order Component
cp Context Provider
cpf Class Property Function

Full Expansions

imr - Import React

import * as React from "react";

imrc - Import React, Component

import * as React from "react";
import { Component } from "react";

imrd - Import ReactDOM

import ReactDOM from "react-dom";

imrs - Import React, useState

import * as React from "react";
import { useState } from "react";

imrse - Import React, useState, useEffect

import * as React from "react";
import { useState, useEffect } from "react";

impt - Import PropTypes

import PropTypes from "prop-types";

impc - Import PureComponent

import * as React from "react";
import { PureComponent } from "react";

cc - Class Component

class | extends React.Component {
  render() {
    return <div>|</div>
  }
}

export default |;

ccc - Class Component With Constructor

class | extends Component {
  constructor(props) {
    super(props);
    this.state = { | };
  }
  render() {
    return ( | );
  }
}

export default |;

cpc - Class Pure Component

class | extends PureComponent {
  state = { | },
  render() {
    return ( | );
  }
}

export default |;

ffc - Function Component

function (|) {
    return ( | );
}

export default |;

sfc - Stateless Function Component (Arrow function)

const | = props => {
  return ( | );
};

export default |;

cdm - componentDidMount

componentDidMount() {
  |
}

uef - useEffect Hook

useEffect(() => {
  |
}, []);

ucb - useCallback Hook

useCallback((val) => {
  |
}, []);

cwm - componentWillMount

//WARNING! To be deprecated in React v17. Use componentDidMount instead.
componentWillMount() {
  |
}

cwrp - componentWillReceiveProps

//WARNING! To be deprecated in React v17. Use new lifecycle static getDerivedStateFromProps instead.
componentWillReceiveProps(nextProps) {
  |
}

gds - getDerivedStateFromProps

static getDerivedStateFromProps(nextProps, prevState) {
  |
}

scu - shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState) {
  |
}

cwu - componentWillUpdate

//WARNING! To be deprecated in React v17. Use componentDidUpdate instead.
componentWillUpdate(nextProps, nextState) {
  |
}

cdu - componentDidUpdate

componentDidUpdate(prevProps, prevState) {
  |
}

cwun - componentWillUnmount

componentWillUnmount() {
  |
}

cdc - componentDidCatch

componentDidCatch(error, info) {
  |
}

gsbu - getSnapshotBeforeUpdate

getSnapshotBeforeUpdate(prevProps, prevState) {
  |
}

ss - setState

this.setState({ | : | });

ssf - Functional setState

this.setState(prevState => {
  return { | : prevState.| }
});

usf - Declare a new state variable using State Hook

const [|, set|] = useState();

Hit Tab to apply CamelCase to function. e.g. [count, setCount]

ren - render

render() {
  return (
    |
  );
}

rprop - Render Prop

class | extends Component {
  state = { | },
  render() {
    return this.props.render({
      |: this.state.|
    });
  }
}

export default |;

hoc - Higher Order Component

function | (|) {
  return class extends Component {
    constructor(props) {
      super(props);
    }

    render() {
      return < | {...this.props} />;
    }
  };
}

cpf - Class Property Function

  | = (e) => {
    |
  }

Commands

React: class to className

Changes all occurences of class in JSX to className. This transform is safe to run multiple times on any document. No text needs to be selected as the command is executed on the entire document.

React: class to className

Thank You! โค๏ธ

While I wrote the initial version of this extension, many people (too many to name) have helped make it what it is today. From providing TypeScript definitions to keeping up with changing API and best practices. If you are enjoying this extension, you have the great React community to thank.

simple-react-snippets's People

Contributors

amingholizad avatar anselal avatar araggohnxd avatar blurbyte avatar burkeholland avatar dependabot[bot] avatar elijahmanor avatar ghosh avatar gilbishkosma avatar hessaam avatar itsjzt avatar jnavb avatar lesleh avatar lud-hu avatar moraesvic avatar movd avatar overra avatar pnhoang avatar rapsalands avatar rbtprograms avatar sshanzel avatar surfinbard avatar thecarlo avatar uazure avatar virtuaboza avatar wkovacs64 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

simple-react-snippets's Issues

Enable simple react snippets extension to run on VS Code on the web

Hey @burkeholland,

Let's try to enable this extension for the web. Might you have time to look into this?
This guide is great https://code.visualstudio.com/api/extension-guides/web-extensions
As a couple of highlights:

  • In VS Code for the Web, both the UI and extension host run inside the browser.
  • A web extension is structured like a regular extension, but with a different main file: it's defined by the browser property
  • Access to workspace files needs to go through the VS Code file system API accessible at vscode.workspace.fs
  • There are currently three ways to test a web extension

I think you just need to add a browser entry point in your package.json. Do you have some node dependencies?

sfc not found

I have just installed version 1.2.4 of Simple React Snippets but sfc is not being found when I type:

image

Other snippets seems to be working, such as ffc as can be seen below:

image

Update setState snippet

Currently the setState expansion is pretty small and doesn't include prevState.

I'd say it'd be a great idea to either add that as a new snippet or improve on the current ss shortcut.

The new expansion will be:

  this.setState(prevState => { 
    return { | :  }
  })

React class property functions

 handleSubmit = e => {
    console.log("Submitted", e.target.value);
  };
"Class property functions": {
	"prefix": "cpf",
	"body": [
		"$1 = (${2:e${TM_SELECTED_TEXT}}) => {",
		"\t $0",
		"};"
	],
	"description": "Class property functions"
	}

when I use ccc there are two exports

hi! I just use ccc but it make some problem
when I typing ccc then it give me this!

export class extends Component {
// I don't want to see export next to the class!
constructor(props) {
super(props);
this.state = { }
}
render() {
return ( )
}
}

export default ;

How could I solve this?

async/await functional components

I recently started working with NextJS and came across async/await functional components

maybe a snippet like arfce

For example

export default async function Foo() {
         return await <div></div>; 
}

Feature Request: Function Components with regular function keyword instead of arrow

This is a feature request.

For function components (which can be statefull using hooks), can we get something like this:

Suggestion of snippet shortcut: >>> ffc

function xxx (xxx) {
  return (xxx);
}
 
export default xxx;

Besides the one we get with >>> sfc:

const  xxx = (xxx) => {
  return (xxx);
}
 
export default xxx;

I think it makes the code more readable.

function myComponent(props) {
  const [state1, setState1] = useState(null);
  const [state2, setState2] = useState(null);
  return(
    <Something>
  );
}

The following way confuses me (with const everywhere):

const MyComponent = (props) => {
  const [state1, setState1] = useState(null);
  const [state2, setState2] = useState(null);
  return(
    <Something>
  );
}

This extension is really helpful.

The extension stopped working with .jsx and VSCode 1.75

After upgrading to VSCode version 1.75, the extension stopped working with files with .jsx extension. I believe it is related to the change "JavaScript React language label is now JavaScript JSX".

The JavaScript React language mode has been renamed to JavaScript JSX to reflect that JSX syntax is used by more than just React. TypeScript React has also been renamed to TypeScript JSX.

VScode showing TypeScript error

Issue Type: Bug

show error that 5 times died typescript Error

Extension version: 1.2.3
VS Code version: Code 1.47.2 (17299e413d5590b14ab0340ea477cdd86ff13daf, 2020-07-15T18:22:06.216Z)
OS version: Windows_NT x64 10.0.18362

System Info
Item Value
CPUs Intel(R) Core(TM) i7-2630QM CPU @ 2.00GHz (8 x 1995)
GPU Status 2d_canvas: enabled
flash_3d: enabled
flash_stage3d: enabled
flash_stage3d_baseline: enabled
gpu_compositing: enabled
multiple_raster_threads: enabled_on
oop_rasterization: unavailable_off
protected_video_decode: unavailable_off
rasterization: unavailable_off
skia_renderer: disabled_off_ok
video_decode: enabled
viz_display_compositor: enabled_on
viz_hit_test_surface_layer: disabled_off_ok
webgl: enabled
webgl2: enabled
Load (avg) undefined
Memory (System) 7.82GB (2.92GB free)
Process Argv .
Screen Reader no
VM 0%

Publish extensions to open-vsx

I'm a VS Codium user, a FLOSS version of VS Code, it's the same code but without the Microsoft's telemetry and branding.
I want to request if possible to add the simple-react-snippets extension on the open-vsx.org market to us doesn't need to works with the Microsoft marketplace as is unclear if it's legal to use it on VS Code forks, see here.

Additional info:

  • This is how to publish a new extension.

Outdated documentation for `fc`

Re: #62, I've found that the function component is present in the snippets.json file, but under the shortcut sfc as in Stateless Function Component.

So probably updating the documentation is the key to fixing #62.

Typscript support

I just installed this and realized it doesn't work with TS and I was going to send a PR to make all the current ones work in TS. I don't think most of them really need types, like ss or impt, those should work the same for js(x)|ts(x) others may have slight variations.

What do you think? Should I send another PR?

BTW, I saw #4 , but the scope looks a bit different.

Remove export default?

Great snippets. However, have you considered removing the default export statements? This is a bit opinionated as others may already have a default export, or avoid using defaults at all.

Publish to OpenVSX

Here are some more details about OpenVSX, its goal, and why it was created

For that reason, I can't use your extension anymore, could you publish on OpenVSX too?
(It's typically just a matter of running npx ovsx publish you can also check the full guide for publishing)

cc vs ccc (both have state)

I noticed that both cc and ccc have state defined in them, but using different techniques (static property vs constructor).

Was adding state to cc intentional? The reason I ask is the trigger for ccc says "Class Component With State" so I was guessing cc was without state.

Was that intentional?

Newline after importing

Just a suggestion, but it would really nice is after an import like imr that the cursor would be placed on the next line, saving having to hit enter after. ๐Ÿ˜„

about suggetions

Type: Bug

when i try to used react snippets i can't get suggetions

Extension version: 1.2.7
VS Code version: Code 1.82.0 (8b617bd08fd9e3fc94d14adb8d358b56e3f72314, 2023-09-06T22:07:07.438Z)
OS version: Windows_NT x64 10.0.22621
Modes:

System Info
Item Value
CPUs Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz (12 x 2904)
GPU Status 2d_canvas: enabled
canvas_oop_rasterization: enabled_on
direct_rendering_display_compositor: disabled_off_ok
gpu_compositing: enabled
multiple_raster_threads: enabled_on
opengl: enabled_on
rasterization: enabled
raw_draw: disabled_off_ok
video_decode: enabled
video_encode: enabled
vulkan: disabled_off
webgl: enabled
webgl2: enabled
webgpu: enabled
Load (avg) undefined
Memory (System) 7.92GB (2.50GB free)
Process Argv --crash-reporter-id d3819e0e-b2e8-4619-958b-6c9f1655107d
Screen Reader no
VM 0%
A/B Experiments
vsliv368:30146709
vsreu685:30147344
python383cf:30185419
vspor879:30202332
vspor708:30202333
vspor363:30204092
vswsl492:30256859
vslsvsres303:30308271
vserr242cf:30382550
pythontb:30283811
vsjup518:30340749
pythonptprofiler:30281270
vshan820:30294714
vstes263:30335439
vscod805cf:30301675
binariesv615:30325510
bridge0708:30335490
bridge0723:30353136
vsaa593:30376534
pythonvs932:30410667
py29gd2263cf:30856253
vsclangdf:30486550
c4g48928:30535728
dsvsc012cf:30540253
pynewext54:30695312
azure-dev_surveyone:30548225
3biah626:30602489
89544117:30613380
showlangstatbar:30737416
0bi6i642:30841073
a2ce3375:30757347
pythonfmttext:30731395
fixshowwlkth:30771522
showindicator:30805244
pythongtdpath:30769146
i26e3531:30792625
pythonnosmt12:30797651
pythonidxpt:30866567
pythonnoceb:30805159
copilotsettingt:30859503
synctok:30869157
dsvsc013:30795093
dsvsc014:30804076
dsvsc015:30845448
pythontestfixt:30871694
pythonregdiag2:30871582
pyreplss1:30865275
pythoncet00cf:30874137
h48ei257:30870396
pythontbext0:30864172

[DISCUSSION] Defaults to single quotes

@burkeholland Is there any possibility i can change the default from single quotes to double quotes ?
when i use shortcut imrs the code snippet is import ...... from 'react', i want it to be import .... "react"; (double quotes)

cc has no state and no () for render

In change log it says

1.0.6
Add state prop to Component Class (cc)
Wrap return from render in () by default for Component Class (cc) and Component Class Constructor (ccc)
Use pipes in README to better articulate tab stops

and I use v1.2.4 and when I type cc it generates this:

class  extends React.Component {
    render() { 
        return <div></div>;
    }
}
 
export default ;

its better to do like this:

class  extends Component {
    state = 
    render() { 
        return (<div></div>);
    }
}
 
export default ;

`fc` function component not found

Hey,

I've added the extension, but when I type fc it only founds the fcc shortcut, which uses the function keyword instead of the arrow function..

image

Why's that?
Would you be able to fix that?

Snippets not showing up

I've installed the extension but the listed snippet shortcuts don't show up in files associated with JavaScript React. Here's my file associations from my user settings:
"files.associations": { "*.vue": "html", "*.js": "javascriptreact" }
I thought maybe it needed to be associated instead with plain JavaScript but that wasn't the case. Any ideas?

Printable PDF Cheatsheet

Hello,

Since I greatly appreciate this project, I created a one-page printable PDF cheat sheet of the popular commands, and shraed attached to this comment. If this is cool, let's roll it into the repo. Yeah?
Simple React Snippets.pdf

Update class snippet

Looking at react documentation, the snippet for class(cc) needs to be updated.

Snippet generated

class  extends Component {
  state = {  }
  render() { 
    return (  );
  }
}
 
export default ;

React Class

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

export default Welcome;

Thanks

Snippets just show up once then disappear

So the snippets only show once after each start of vscode, im using jsx extension and here is my vscode install

Version: 1.41.1 (system setup)
Commit: 26076a4de974ead31f97692a0d32f90d735645c0
Date: 2019-12-18T14:58:56.166Z
Electron: 6.1.5
Chrome: 76.0.3809.146
Node.js: 12.4.0
V8: 7.6.303.31-electron.0
OS: Windows_NT x64 10.0.18362

PropTypes snippets

It would be good to have a snippets for defining proptypes. Check the following example. I used "|" as a placeholder for cursor.

after typing pt:

|.propTypes = {
  |: PropTypes.|,
}

after typing dp:

|.defaultProps = {
  |,
};

Snippets work sporadically.

Hey folks! I m still facing this issue where I can't see the snippent. I m currently on version 1.2.7
image

But if I declare a variable of any kind, it works just fine, but it becomes quite pointless at that moment:
image

Here's a clip that can explain this to you better:
Simple React Snippets_Issue

Here are my file associations from my user settings:
image

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.