React Cheat Sheet

React is a free and open-source front-end JavaScript library for building user interfaces based on UI components. It is maintained by Meta and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.

Create new react project

npm -v
npm i npx
npx create-react-app my-react-app
cd my-react-app
code .

Run from terminal

npm start

OR

npm start --port 8000

Open Browser and run the react app http://localhost:3000 OR http://ipaddress:3000

App.js

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <>
      <h1>Test App</h1>
    </>
  );
}

export default App;

Create new component and use click and change event

src/components/Add.js

import { Fragment, useState } from "react";


function Add () {

    const [ num1, setNum1 ] = useState(0);
    const [ num2, setNum2 ] = useState(0);
    const [ result, setResult ] = useState(0);

    function addFun() {
        setResult(num1 + num2);
    }

    return (<Fragment>
        <h1>Addition of two numbers</h1>
        <input type="text" onChange={ e => setNum1(parseInt(e.target.value)) }/>
        <input type="text" onChange={ e => setNum2(parseInt(e.target.value)) } />
        <button onClick={addFun}>Get Addtion</button>
        <div>{result}</div>
    </Fragment>);
}

export default Add;

Add this Add component in App component as tag <Add />

import './App.css';
import Add from './components/Add';

function App() {
  return (
    <>
      <Add />
      <Add />
      <h1>Test App</h1>
    </>
  );
}

export default App;

React Properties

App.js

import './App.css';
import Add from './components/Add';

function App() {
  return (
    <>
      <Add x="5" y="6"/>
      <Add x="7" y="8"/>
      <h1>Test App</h1>
    </>
  );
}

export default App;

Add.js

import { Fragment, useState } from "react";


function Add (props) {

    const [ num1, setNum1 ] = useState(parseInt(props.x));
    const [ num2, setNum2 ] = useState(parseInt(props.y));
    const [ result, setResult ] = useState(0);

    function addFun() {
        setResult(num1 + num2);
    }

    return (<Fragment>
        <h1>Addition of two numbers</h1>
        <input type="text" onChange={ e => setNum1(parseInt(e.target.value)) }/>
        <input type="text" onChange={ e => setNum2(parseInt(e.target.value)) } />
        <button onClick={addFun}>Get Addtion</button>
        <div>{result}</div>
    </Fragment>);
}

export default Add;

Ajax call in React.js

Create new component Users

components/User.js

import { Fragment } from "react";

function User(props) {

    //object destructoring assignment
    const {id, name, username, email} = props.user;

    return (
        <Fragment>
            <tr>
                <td>{props.user.id}</td> 
                <td>{props.user.name}</td>
                <td>{username}</td>  
                <td>{email}</td>
            </tr>
        </Fragment>
    );

}

export default User;

components/UsersListing.js

import { Fragment, useState } from "react";
import User from "./User";

function UsersListing () {

    const [ users, setUsers ] = useState([]);


    function getUsers() {

        fetch("https://jsonplaceholder.typicode.com/users")
        .then(response => response.json())
        .then(json => {
                console.table(json)
                var rows = [];
                for(let i = 0; i < json.length; i++) {
                    rows.push(<User key={i} user={json[i]}/>);
                }
                setUsers(rows);
            }
        );

    }

    return (<Fragment>
        <h1>Users Listing</h1>
        
        <button onClick={getUsers}>Get Users</button>

        <table border='1'>
            <thead>
                <th>Id</th>
                <th>Name</th>
                <th>Username</th>
                <th>Email</th>
            </thead>
            <tbody>
                {users}
            </tbody>
        </table>
    </Fragment>);
}

export default UsersListing;

Use <UsersListing /> component in App.js JSX to show users list

Routing

https://www.w3schools.com/REACT/react_router.asp

Deploy React App on Github

Create repository on github

git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/<username>/<repositoryname>.git
git remote set-url origin https://<githubtoken>@github.com/<username>/<repositoryname>.git
#git clone https://<username>:<githubtoken>@github.com/<username>/<repositoryname>.git

To get github token Go To Profile Settings => Developer Settings => Personal Access Token => Generate New Token

npm install gh-pages --save-dev

vim package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "homepage": "https://gitname.github.io/repositoryname",
  "private": true,
  
  
 "scripts": {
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "start": "react-scripts start",
    "build": "react-scripts build",
npm run deploy
git status
git add .
git commit -m 'deploy react on github'
git push

https://<username>.github.io/<repositoryname>/

To publish react app locally

npm run build

Verify build directory and index.html file

build/index.html

<link rel="manifest" href="manifest.json"/>
<title>React App</title>
<script defer="defer" src="./static/js/main.<yourhash>.js"></script>
<link href="./static/css/main.<yourhash>.css" rel="stylesheet">

You can publish this in xampp htdocs folder

Leave a Reply

Your email address will not be published. Required fields are marked *