# React

## 01. [Getting Started](https://create-react-app.dev/docs/getting-started)

```bash
## ------------------| Create 
npm init react-app myapp
cd myapp
npm start

## ------------------| Deploy to production
npm run build
```

## 02. React Hooks

* [useState](https://reactjs.org/docs/hooks-state.html)

```bash
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

```javascript
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

```jsx
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

```bash
## ------------------| First need to install nodejs LTS version
sudo apt-get update
sudo apt-get upgrade
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

## ------------------| Then we need to install expo cli
npm install -g expo-cli
```

### 04.2 Create my FirstProject

```bash
## ------------------| Creatre FirstProject
expo init FirstProject
cd 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.js
mkdir components
touch components/styles.js

## Then we need to create another directory call screens; this is where we create all screens
touch screens/Login.js
touch screens/Home.js

## then we need to install some expo dependencies.
expo install formik styled-components expo-constants

## After all you can run 
npm start # you can also use: expo start
```

* Inside the styles.js

```javascript
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

```javascript
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

```javascript
import React from 'react';

//Import Login.js
import Login from './screens/Login'

export default function App() {
  return <Login/>
}              
```

### 04.3 Generate release apk file.

```bash
### Create keystore file at <YourProject>/android/app/routerspace.keystore
keytool -genkey -v -keystore <keyName>.keystore -alias <your_key_alias> -keyalg RSA -keysize 2048 -validity 10000        

### Edit this file <YourProject>/android/app/build.gradle 
android {
....
  signingConfigs {
    release {
      storeFile file('<keyName>.keystore')
      storePassword 'password123'
      keyAlias '<your_key_alias>'
      keyPassword 'password123'
    }
  }

  buildTypes {
    release {
      ....
      signingConfig signingConfigs.release

    }
  }
}

### Execute this command
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/       

### Release APK Generation
cd 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

```bash
https://www.npmjs.com/package/axios
https://www.npmjs.com/package/formik
https://www.npmjs.com/package/obfuscator-io-metro-plugin
https://www.npmjs.com/package/react-native-toast-message
https://www.npmjs.com/package/react-native-app-intro-slider
https://github.com/react-native-device-info/react-native-device-info
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.h4rithd.com/languages/react.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
