React Snippets
Import classNames, styles
react-classnames-styles
import classNames from 'classnames/bind';
import styles from '.';
const cx = classNames.bind(styles);
Export Component
react-export-component
export {default} from '.'
useState
useState
const [$1, set$1] = useState($2)
## useEffect
<code>useEffect</code>
```bash
useEffect(() => {
}, [])
Get daa
getData
useEffect(() => {,
async function getData() {,
$1,
},
,
getData();,
}, [])
React Native Snippets
React native navigation
rnnavigation
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="" component={} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Create file app with tab navigation
rntabnavigation
import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
const Tab = createBottomTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="" component={} />
</Tab.Navigator>
</NavigationContainer>
);
}
Create file app with drawer navigation
rndrawernavigation
import React from 'react';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="">
<Drawer.Screen name="" component={} />
</Drawer.Navigator>
</NavigationContainer>
);
}
Create react native component
rncomponent
import { StyleSheet, View } from 'react-native';
import React from 'react';
export default function test() {
return <View></View>;
}
const styles = StyleSheet.create({});
Create customize tab bar
rntabbar
import { View, Text, TouchableOpacity } from 'react-native';
function test({ state, descriptors, navigation }) {
return (
<View style={{ flexDirection: 'row' }}>
{state.routes.map((route, index) => {
const { options } = descriptors[route.key];
const label =
options.tabBarLabel !== undefined
? options.tabBarLabel
: options.title !== undefined
? options.title
: route.name;
const isFocused = state.index === index;
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
canPreventDefault: true,
});
if (!isFocused && !event.defaultPrevented) {
navigation.navigate(route.name, route.params);
}
};
const onLongPress = () => {
navigation.emit({
type: 'tabLongPress',
target: route.key,
});
};
return (
<TouchableOpacity
accessibilityRole="button"
accessibilityState={isFocused ? { selected: true } : {}}
accessibilityLabel={options.tabBarAccessibilityLabel}
testID={options.tabBarTestID}
onPress={onPress}
onLongPress={onLongPress}
style={{ flex: 1 }}
>
<Text style={{ color: isFocused ? '#673ab7' : '#222' }}>
{label}
</Text>
</TouchableOpacity>
);
})}
</View>
);
}
export default test
Create image
rnimage
<Image source={} style={{width: , height: } />
React native flatlist
rnflatlist
<FlatList
data={}
renderItem={({item}) => }
keyExtractor={item => }
/>
React native KeyboardAvoidingView
rnKeyboardAvoidingView
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={{}}
></KeyboardAvoidingView>;
React native SectionList
rnSectionList
<SectionList
sections={}
keyExtractor={(item, index) => }
renderItem={({item}) => (
)}
renderSectionHeader={({section: {title}}) => (
)}
/>
React native TextInput
rnTextInput
<TextInput
style={}
onChangeText={}
value={}
/>
React native ActivityIndicator
rnActivityIndicator
<ActivityIndicator
size='large'
style={styles.loading}
animating={true}
color={MD2Colors.red800}
/>
React native SafeAreaView
rnSafeAreaView
<SafeAreaView
style={[{
marginTop: StatusBar.currentHeight || 0
}]}>
</SafeAreaView>
Fetch API
Fetch post
fetchpost
const res = await fetch(`ENDPOINT/`, {
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
method: 'post',
body: JSON.stringify(),
});
const data = await res.json();
console.log('🚀 ~ data:', data);
Fetch get
fetchget
const res = await fetch(`ENDPOINT/`);
const data = await res.json();
console.log('🚀 ~ data:', data);
Fetch put
fetchput
const res = await fetch(`ENDPOINT/`, {
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
method: 'put',
body: JSON.stringify(),
});
const data = await res.json();
console.log('🚀 ~ data:', data);
Fetch delete
fetchdelete
const res = await fetch(`ENDPOINT/`, {
method: 'delete',
});
const data = await res.json();
console.log('🚀 ~ data:', data);
Redux Create Store
rxcs
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: false,
})
})
Redux Create Slice
rxslice
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
}
export const Slice = createSlice({
name: '',
initialState,
reducers: {
},
})
export const { } = Slice.actions
export default Slice.reducer
Create dispatch
dispatch
const dispatch = useDispatch();
Create selector
selector
const {} = useSelector((state) => state.$1);
Create reducer in slice
rxreducerslice
: (state, { payload }) => {
}
Redux Async Thunk
rxcreateasyncthunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await
return response.data
}
)
rxextrareducers
extraReducers: (builder) => {
builder.addCase(fetchUserById.fulfilled, (state, action) => {
state.entities.push(action.payload);
});
};
Redux Service
Redux Service
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const userApi = createApi({
reducerPath: '',
baseQuery: fetchBaseQuery({ baseUrl: }),
endpoints: (builder) => ({
// getPokemonByName: builder.query({
// query: (name) => `pokemon/name`,
// }),
}),
});
export const {} = userApi;
SQLite
Create a metro.config.js file at the root of your project
sqliteConfig
const { getDefaultConfig } = require('expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('db');
module.exports = defaultConfig;
Open DB
sqliteOpenDB
import * as SQLite from 'expo-sqlite';
function openDatabase() {
if (Platform.OS === 'web') {
return {
transaction: () => {
return {
executeSql: () => {},
};
},
};
}
const db = SQLite.openDatabase('db.db');
db.exec([{ sql: 'PRAGMA foreign_keys = ON;', args: [] }], false, () =>
console.log('Foreign keys turned on'),
);
return db;
}
export default openDatabase;
export const db = openDatabase();
Create Table
sqliteCreateTable
db.transaction((tx) => {
tx.executeSql(
'create table if not exists (id integer primary key not null, );',
);
tx.executeSql('SELECT * FROM ', [], (_, { rows: { _array } }) => {});
});
Insert item into table
sqliteInsert
db.transaction((tx) => {
tx.executeSql('insert into () values ()', [], (tx, { insertId }) => {
tx.executeSql(
'select * from WHERE id = ?',
[insertId],
(_, { rows: { _array } }) => {},
);
});
});
Update item in table
sqliteUpdate
db.transaction((tx) => {
tx.executeSql('UPDATE SET WHERE id = ?', [, data.id], () => {});
});
Delete item in table
sqliteDelete
const res = await db.execAsync(
[
{
sql: 'DELETE FROM WHERE ',
args: [],
},
],
false,
);
if (Number.isInteger(res?.[0]?.insertId)) {
// Success
} else {
// Error
}
SQLite Type
sqliteType
Snippets
{
"ClassNames-Styles": {
"scope": "javascript,typescript",
"prefix": "react-classnames-styles",
"body": [
"import classNames from 'classnames/bind';",
"import styles from '.$1';",
"",
"const cx = classNames.bind(styles);"
],
"description": "Import classNames, styles"
},
"Export Component": {
"scope": "javascript,typescript",
"prefix": "react-export-component",
"body": [
"export {default} from '.$1'"
],
"description": "Export Component"
},
"React native navigation": {
"scope": "javascript,typescript",
"prefix": "rnnavigation",
"body": [
"import React from 'react';",
"import { NavigationContainer } from '@react-navigation/native';",
"import { createNativeStackNavigator } from '@react-navigation/native-stack';",
"",
"const Stack = createNativeStackNavigator();",
"",
"function App() {",
" return (",
" <NavigationContainer>",
" <Stack.Navigator>",
" <Stack.Screen name=\"$1\" component={$2} />",
" </Stack.Navigator>",
" </NavigationContainer>",
" );",
"}",
"",
"export default App;"
],
"description": "Create file app is navigation"
},
"Create file app with tab navigation": {
"scope": "javascript,typescript",
"prefix": "rntabnavigation",
"body": [
"import * as React from 'react';",
"import { Text, View } from 'react-native';",
"import { NavigationContainer } from '@react-navigation/native';",
"import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';",
"",
"const Tab = createBottomTabNavigator();",
"",
"export default function App() {",
" return (",
" <NavigationContainer>",
" <Tab.Navigator>",
" <Tab.Screen name=\"$1\" component={$2} />",
" </Tab.Navigator>",
" </NavigationContainer>",
" );",
"}"
],
"description": "Create file app with tab navigation"
},
"Create file app with drawer navigation": {
"scope": "javascript,typescript",
"prefix": "rndrawernavigation",
"body": [
"import React from 'react';",
"import { createDrawerNavigator } from '@react-navigation/drawer';",
"import { NavigationContainer } from '@react-navigation/native';",
"",
"const Drawer = createDrawerNavigator();",
"",
"export default function App() {",
" return (",
" <NavigationContainer>",
" <Drawer.Navigator initialRouteName=\"$1\">",
" <Drawer.Screen name=\"$2\" component={$3} />",
" </Drawer.Navigator>",
" </NavigationContainer>",
" );",
"}"
],
"description": "Create file app with drawer navigation"
},
"Create react native component": {
"prefix": "rncomponent",
"body": [
"import { StyleSheet, View } from 'react-native';",
"import React from 'react';",
"",
"export default function $TM_FILENAME_BASE() {",
" return <View></View>;",
"}",
"",
"const styles = StyleSheet.create({});"
],
"description": "Create react native component"
},
"Create customize tab bar": {
"prefix": "rntabbar",
"body": [
"import { View, Text, TouchableOpacity } from 'react-native';",
"",
"function $TM_FILENAME_BASE({ state, descriptors, navigation }) {",
" return (",
" <View style={{ flexDirection: 'row' }}>",
" {state.routes.map((route, index) => {",
" const { options } = descriptors[route.key];",
" const label =",
" options.tabBarLabel !== undefined",
" ? options.tabBarLabel",
" : options.title !== undefined",
" ? options.title",
" : route.name;",
"",
" const isFocused = state.index === index;",
"",
" const onPress = () => {",
" const event = navigation.emit({",
" type: 'tabPress',",
" target: route.key,",
" canPreventDefault: true,",
" });",
"",
" if (!isFocused && !event.defaultPrevented) {",
" navigation.navigate(route.name, route.params);",
" }",
" };",
"",
" const onLongPress = () => {",
" navigation.emit({",
" type: 'tabLongPress',",
" target: route.key,",
" });",
" };",
"",
" return (",
" <TouchableOpacity",
" accessibilityRole=\"button\"",
" accessibilityState={isFocused ? { selected: true } : {}}",
" accessibilityLabel={options.tabBarAccessibilityLabel}",
" testID={options.tabBarTestID}",
" onPress={onPress}",
" onLongPress={onLongPress}",
" style={{ flex: 1 }}",
" >",
" <Text style={{ color: isFocused ? '#673ab7' : '#222' }}>",
" {label}",
" </Text>",
" </TouchableOpacity>",
" );",
" })}",
" </View>",
" );",
"}",
"",
"export default $TM_FILENAME_BASE"
],
"description": "Create customize tab bar"
},
"Fetchpost": {
"prefix": "fetchpost",
"body": [
"const res = await fetch(`${ENDPOINT}/$1`, {",
" headers: {",
" 'Content-type': 'application/json; charset=UTF-8',",
" },",
" method: 'post',",
" body: JSON.stringify($2),",
"});",
"const data = await res.json();",
"",
"console.log('🚀 ~ data:', data);"
],
"description": "Fetch"
},
"Fetchget": {
"prefix": "fetchget",
"body": [
"const res = await fetch(`${ENDPOINT}/$1`);",
"const data = await res.json();",
"",
"console.log('🚀 ~ data:', data);"
],
"description": "Fetch"
},
"Fetchput": {
"prefix": "fetchput",
"body": [
"const res = await fetch(`${ENDPOINT}/$1`, {",
" headers: {",
" 'Content-type': 'application/json; charset=UTF-8',",
" },",
" method: 'put',",
" body: JSON.stringify($2),",
"});",
"const data = await res.json();",
"",
"console.log('🚀 ~ data:', data);"
],
"description": "Fetchput"
},
"Fetchdelete": {
"prefix": "fetchdelete",
"body": [
"const res = await fetch(`${ENDPOINT}/$1`, {",
" method: 'delete',",
"});",
"const data = await res.json();",
"",
"console.log('🚀 ~ data:', data);"
],
"description": "Fetchdelete"
},
"Redux Service": {
"prefix": "reduxservice",
"body": [
"import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';",
"",
"export const userApi = createApi({",
" reducerPath: '$1',",
" baseQuery: fetchBaseQuery({ baseUrl: $2 }),",
" endpoints: (builder) => ({",
" // getPokemonByName: builder.query({",
" // query: (name) => `pokemon/${name}`,",
" // }),",
" }),",
"});",
"",
"export const {} = userApi;",
""
],
"description": "Redux Service"
},
"Redux - Create store": {
"prefix": "rxcs",
"body": [
"import { configureStore } from '@reduxjs/toolkit'",
"",
"export const store = configureStore({",
" reducer: {},",
" middleware: (getDefaultMiddleware) =>"
" getDefaultMiddleware({"
" serializableCheck: false,"
" })"
"})"
],
"description": "Redux - Create store"
},
"Redux - Create slice": {
"prefix": "rxslice",
"body": [
"import { createSlice } from '@reduxjs/toolkit'",
"",
"const initialState = {",
"}",
"",
"export const $1Slice = createSlice({",
" name: '$1',",
" initialState,",
" reducers: {",
" },",
"})",
"",
"export const { } = $1Slice.actions",
"",
"export default $1Slice.reducer"
],
"description": "Redux - Create slice"
},
"Redux Async Thunk": {
"prefix": "rxcreateasyncthunk",
"body": [
"const fetchUserById = createAsyncThunk(",
" 'users/fetchByIdStatus',",
" async (userId, thunkAPI) => {",
" const response = await $1",
" return response.data",
" }",
")"
],
"description": "Redux Async Thunk"
},
"Redux Extra Reducers": {
"prefix": "rxextrareducers",
"body": [
"extraReducers: (builder) => {",
" builder.addCase(fetchUserById.fulfilled, (state, action) => {",
" state.entities.push(action.payload)",
" })",
" }"
],
"description": "Redux Extra Reducers"
},
"React native flatlist": {
"prefix": "rnflatlist",
"body": [
"<FlatList",
" data={$1}",
" renderItem={({item}) => $2}",
" keyExtractor={item => $3}",
"/>"
],
"description": "React native flatlist"
},
"React native KeyboardAvoidingView": {
"prefix": "rnKeyboardAvoidingView",
"body": [
"<KeyboardAvoidingView",
" behavior={Platform.OS === 'ios' ? 'padding' : 'height'}",
" style={{$1}}>",
"</KeyboardAvoidingView>"
],
"description": "React native KeyboardAvoidingView"
},
"React native SectionList": {
"prefix": "rnSectionList",
"body": [
"<SectionList",
" sections={$1}",
" keyExtractor={(item, index) => $2}",
" renderItem={({item}) => (",
" $3",
" )}",
" renderSectionHeader={({section: {title}}) => (",
" $4",
" )}",
" />"
],
"description": "React native SectionList"
},
"React native TextInput": {
"prefix": "rnTextInput",
"body": [
"<TextInput",
" style={$1}",
" onChangeText={$2}",
" value={$3}",
" />"
],
"description": "React native TextInput"
},
"React native ActivityIndicator": {
"prefix": "rnActivityIndicator",
"body": [
"<ActivityIndicator",
" size='large'",
" style={styles.loading}",
" animating={true}",
" color={MD2Colors.red800}",
" />"
],
"description": "React native ActivityIndicator"
},
"React native SafeAreaView": {
"prefix": "rnSafeAreaView",
"body": [
"<SafeAreaView style={[{marginTop: StatusBar.currentHeight || 0}]}>",
" </SafeAreaView>"
],
"description": "React native SafeAreaView"
},
"React native image": {
"prefix": "rnimage",
"body": [
"<Image source={$1} style={{width: $2, height: $2} />"
],
"description": "Create image"
},
}