13Languages
React
01 Getting Started
bash7 lines
## ------------------| Createnpm init react-app myappcd myappnpm start
## ------------------| Deploy to productionnpm run build02 React Hooks
bash14 lines
import React, { useState } from 'react';
function App() { const [value, setValue] = useState("This is initial value");
return ( <div> <button onClick={() => setValue("Value changed")}>Default</button> <h1>{value}</h1> </div> );}
export default App;03 Back-End Integration
- Fetching data from backend when page loads
javascript23 lines
import React, { useEffect, useState } from 'react';
function App() { const [results, setResults] = useState("");
useEffect(() => { const fetchResults = async () => { const response = await fetch("https://h4rithd.com/test"); const responseObj = await response.text(); setResults(responseObj); // For JSON objects // const responseObj = await response.json(); // setResults(responseObj.value); }; fetchResults(); }, []);
return ( <p>{results}</p> );}
export default App;- Submitting data to backend
jsx40 lines
import React, { useState } from 'react';
function App() {
const [form, setForm] = useState({ item: "", });
const createItemSubmit = (e) => { e.preventDefault(); // Prevent refeshing the page fetch("https://h4rithd.com/test", { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'Content-Type': 'application/json' // or 'application/x-www-form-urlencoded' }, redirect: 'follow', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: JSON.stringify(form) }); };
return ( <div> <form> <input onChange={(e) => setForm({ ...form, item: e.target.value })} name="item"></input> <button type="submit" onClick={createItemSubmit}>Submit</button> </form> </div> );}
export default App;04 Create first app.
04.1 Setup environment
bash8 lines
## ------------------| First need to install nodejs LTS versionsudo apt-get updatesudo apt-get upgradecurl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -sudo apt-get install -y nodejs
## ------------------| Then we need to install expo clinpm install -g expo-cli04.2 Create my FirstProject
bash28 lines
## ------------------| Creatre FirstProjectexpo init FirstProjectcd FirstProject
## Then we need to create .prettierrc file and past following content.## this will create same configaration for all pcs{ "printWidth": 120, "tabWidth":2, "useTabs": false, "semi":true. "singleQuote": true, "trailingComma":"all"}
## Then create components directory. this is whre we store some files like styles.jsmkdir componentstouch components/styles.js
## Then we need to create another directory call screens; this is where we create all screenstouch screens/Login.jstouch screens/Home.js
## then we need to install some expo dependencies.expo install formik styled-components expo-constants
## After all you can runnpm start # you can also use: expo start- Inside the styles.js
javascript37 lines
import styled from 'styled-components';import { View, Text } from 'react-native';import Constants from 'expo-constants';
const StatusBarHeight = Constants.statusBarHeight; // to get hight of the status bar
//colors; you can use https://colors.muz.li/export const Colors ={ primary: '#FAF9F9', //Cultured secondary: '#BEE3DB', //Powder Blue tertiary: '#89B0AE', //Morning Blue brand: '555B6E', //Independence white: 'ffffff', green: '40916c', red: 'ff4d6d',};
const { primary, secondary, tertiary, brand, white, green, red } = Colors;
export const StyledContainer = styled.View` flex: 1; padding: 25px; padding-top: ${StatusBarHeight + 10}px; background-color: ${primary};`export const InnerContainer = styled.View` flex: 1; width: 100%; align-items: center;`export const PageTitle = styled.Text` font-size: 30px; text-align: center; font-weight: bold; color: ${brand}; padding: 10px;`- Login.js
javascript24 lines
import React from "react";import { StatusBar } from 'expo-status-bar';
import { StyledContainer, InnerContainer, PageTitle} from './../components/styles'
const Login = () => { return( <StyledContainer> <StatusBar style="dark"/> <InnerContainer> <PageTitle> Hello World </PageTitle> </InnerContainer> </StyledContainer>
);}
export default Login;- App.js
javascript8 lines
import React from 'react';
//Import Login.jsimport Login from './screens/Login'
export default function App() { return <Login/>}04.3 Generate release apk file.
bash34 lines
### Create keystore file at <YourProject>/android/app/routerspace.keystorekeytool -genkey -v -keystore <keyName>.keystore -alias <your_key_alias> -keyalg RSA -keysize 2048 -validity 10000
### Edit this file <YourProject>/android/app/build.gradleandroid {.... signingConfigs { release { storeFile file('<keyName>.keystore') storePassword 'password123' keyAlias '<your_key_alias>' keyPassword 'password123' } }
buildTypes { release { .... signingConfig signingConfigs.release
} }}
### Execute this commandnpx react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
### Release APK Generationcd android./gradlew assembleRelease
### If you get any errors, then try this.rm -rf android/app/src/main/res/drawable-*npx react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/05 Useful packages
bash6 lines
https://www.npmjs.com/package/axioshttps://www.npmjs.com/package/formikhttps://www.npmjs.com/package/obfuscator-io-metro-pluginhttps://www.npmjs.com/package/react-native-toast-messagehttps://www.npmjs.com/package/react-native-app-intro-sliderhttps://github.com/react-native-device-info/react-native-device-info