react-native-sop-docs/03-development-standards/vscode-snippets.md

6.2 KiB

VSCode Snippets

Setup VSCode Snippets

Create .vscode/snippets.code-snippets in your project root:

{
  "React Native Functional Component": {
    "prefix": "rnfc",
    "body": [
      "import React from 'react';",
      "import {View, Text, StyleSheet} from 'react-native';",
      "",
      "interface ${1:ComponentName}Props {",
      "  $2",
      "}",
      "",
      "export const ${1:ComponentName}: React.FC<${1:ComponentName}Props> = ({$3}) => {",
      "  return (",
      "    <View style={styles.container}>",
      "      <Text>$4</Text>",
      "    </View>",
      "  );",
      "};",
      "",
      "const styles = StyleSheet.create({",
      "  container: {",
      "    flex: 1,",
      "  },",
      "});"
    ],
    "description": "Create a React Native functional component"
  },
  
  "React Native Screen Component": {
    "prefix": "rnscreen",
    "body": [
      "import React from 'react';",
      "import {View, Text, StyleSheet, SafeAreaView} from 'react-native';",
      "import {CHeader} from '@components/common';",
      "",
      "interface ${1:ScreenName}Props {",
      "  navigation: any;",
      "  route: any;",
      "}",
      "",
      "export const ${1:ScreenName}: React.FC<${1:ScreenName}Props> = ({navigation, route}) => {",
      "  return (",
      "    <SafeAreaView style={styles.container}>",
      "      <CHeader",
      "        title=\"${2:Screen Title}\"",
      "        onBackPress={() => navigation.goBack()}",
      "      />",
      "      <View style={styles.content}>",
      "        <Text>$3</Text>",
      "      </View>",
      "    </SafeAreaView>",
      "  );",
      "};",
      "",
      "const styles = StyleSheet.create({",
      "  container: {",
      "    flex: 1,",
      "    backgroundColor: '#FFFFFF',",
      "  },",
      "  content: {",
      "    flex: 1,",
      "    padding: 16,",
      "  },",
      "});"
    ],
    "description": "Create a React Native screen component"
  },

  "Redux Slice": {
    "prefix": "reduxslice",
    "body": [
      "import {createSlice, PayloadAction} from '@reduxjs/toolkit';",
      "",
      "interface ${1:SliceName}State {",
      "  $2",
      "}",
      "",
      "const initialState: ${1:SliceName}State = {",
      "  $3",
      "};",
      "",
      "const ${4:sliceName}Slice = createSlice({",
      "  name: '${4:sliceName}',",
      "  initialState,",
      "  reducers: {",
      "    ${5:actionName}: (state, action: PayloadAction<$6>) => {",
      "      $7",
      "    },",
      "  },",
      "});",
      "",
      "export const {${5:actionName}} = ${4:sliceName}Slice.actions;",
      "export default ${4:sliceName}Slice.reducer;"
    ],
    "description": "Create a Redux Toolkit slice"
  },

  "API Service": {
    "prefix": "apiservice",
    "body": [
      "import {createApi, fetchBaseQuery} from '@reduxjs/toolkit/query/react';",
      "import Config from 'react-native-config';",
      "",
      "export const ${1:serviceName}Api = createApi({",
      "  reducerPath: '${1:serviceName}Api',",
      "  baseQuery: fetchBaseQuery({",
      "    baseUrl: `\\${Config.API_BASE_URL}/${2:endpoint}`,",
      "    prepareHeaders: (headers, {getState}) => {",
      "      const token = (getState() as any).auth.token;",
      "      if (token) {",
      "        headers.set('authorization', `Bearer \\${token}`);",
      "      }",
      "      return headers;",
      "    },",
      "  }),",
      "  tagTypes: ['${3:TagType}'],",
      "  endpoints: builder => ({",
      "    ${4:endpointName}: builder.query({",
      "      query: () => '/${5:path}',",
      "      providesTags: ['${3:TagType}'],",
      "    }),",
      "  }),",
      "});",
      "",
      "export const {use${6:EndpointName}Query} = ${1:serviceName}Api;"
    ],
    "description": "Create an RTK Query API service"
  },

  "React Hook": {
    "prefix": "rnhook",
    "body": [
      "import {useState, useEffect} from 'react';",
      "",
      "interface Use${1:HookName}Return {",
      "  $2",
      "}",
      "",
      "export const use${1:HookName} = ($3): Use${1:HookName}Return => {",
      "  const [${4:state}, set${5:State}] = useState($6);",
      "",
      "  useEffect(() => {",
      "    $7",
      "  }, []);",
      "",
      "  return {",
      "    ${4:state},",
      "    set${5:State},",
      "    $8",
      "  };",
      "};"
    ],
    "description": "Create a custom React hook"
  },

  "Test Component": {
    "prefix": "rntest",
    "body": [
      "import React from 'react';",
      "import {render, fireEvent} from '@testing-library/react-native';",
      "import {${1:ComponentName}} from '../${1:ComponentName}';",
      "",
      "describe('${1:ComponentName}', () => {",
      "  it('renders correctly', () => {",
      "    const {getByText} = render(<${1:ComponentName} $2 />);",
      "    expect(getByText('$3')).toBeTruthy();",
      "  });",
      "",
      "  it('$4', () => {",
      "    const mock${5:Function} = jest.fn();",
      "    const {getByText} = render(",
      "      <${1:ComponentName} ${6:prop}={mock${5:Function}} $7 />",
      "    );",
      "    ",
      "    fireEvent.press(getByText('$8'));",
      "    expect(mock${5:Function}).toHaveBeenCalledTimes(1);",
      "  });",
      "});"
    ],
    "description": "Create a test file for a component"
  }
}

Usage

After creating the snippets file, you can use these shortcuts in VSCode:

  • rnfc - Creates a functional component
  • rnscreen - Creates a screen component with navigation
  • reduxslice - Creates a Redux Toolkit slice
  • apiservice - Creates an RTK Query API service
  • rnhook - Creates a custom React hook
  • rntest - Creates a test file template

Additional Snippets

You can extend the snippets file with more specific patterns used in your project:

{
  "Styled Component": {
    "prefix": "rnstyle",
    "body": [
      "const styles = StyleSheet.create({",
      "  ${1:styleName}: {",
      "    $2",
      "  },",
      "});"
    ],
    "description": "Create StyleSheet styles"
  },

  "Navigation Type": {
    "prefix": "navtype",
    "body": [
      "type ${1:StackName}ParamList = {",
      "  ${2:ScreenName}: {${3:param}: ${4:type}};",
      "  ${5:AnotherScreen}: undefined;",
      "};"
    ],
    "description": "Create navigation param list type"
  }
}