Cheat Sheet: REACT

To start with:

index.js

import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("root"));

indext.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>xxx</title>
<link rel="stylesheet" href="styles.css" />
</head>

<body>
<div id="root"></div>
<script src="../src/index.js" type="text/JSX"></script>
</body>
</html>

.css styling

const img = "https://picsum.photos/200";

ReactDOM.render(
<div>
<h1 className="heading">My Favourite Foods</h1>
<img alt="random" src={img + "?grayscale"} />
</div>,
document.getElementById("root")
);
//camelCase for JSX attributes

inline styling (for dynamic styling needs)

const customStyle = { // different from CSS, need to add "" in the value
color: "red",
fontSize: "20px",
border: "1px solid black"
};

customStyle.color = "blue";

ReactDOM.render(
<div>
<h1 style={customStyle}>Hello World!</h1>
<h1 style={{color:"red"}}>Hello World!</h1>
//two {{}} as JSX is expecting an object
</div>,
document.getElementById("root")
);

React Component

components/heading.js
import React from "react";

function Heading() {
return <h1>My Favourite Foods</h1>;
}

export default Heading;
components/content.js
import React from "react";

function Content() {
return (
<ul>
<li>Bacon</li>
<li>Jamon</li>
<li>Noodles</li>
</ul>
);
}

export default Content;
components/app.js
import React from "react";
import Heading from "./Heading";
import Content from "./Content";

function App() {
return (
<div>
<Heading />
<Content />
</div>
);
}

export default App;
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";

ReactDOM.render(<App />, document.getElementById("root"));

Export / Import default / multiple module

index.js
import pi, { doublePi, triplePi } from "./component.js";

ReactDOM.render(
<ul>
<li>{pi}</li>
<li>{doublePi()}</li>
<li>{triplePi()}</li>
</ul>,
document.getElementById("root")
);

component.js

...
export default pi;
export { doublePi, triplePi };

React Component

props

component.js
function Card(props) {
return (
<div>
<div>
<h2>{props.name}</h2>
<img src={props.img} />
</div>
<div >
<p >{props.tel}</p>
<p >{props.email}</p>
</div>
</div>
);
}
export...
app.js
function App() {
return (
<div>
<Card
name="Beyonce"
img="https://1.com/jpg.jpg"
tel="12343543"
email="xiasf@mail.com"
/>
</div>
);
}

Loop Through

create a function
function createCard(contact) {
return (
<Card
key={contact.id}
name={contact.name}
img={contact.imgURL}
tel={contact.phone}
email={contact.email}
/>
);
}

export array in the data.js
export default contacts; //No need to import React

Use .map()
import contacts from "../data";
function App() {
return (
<div>
<h1 className="heading">My Contacts</h1>
{contacts.map(createCard)}
</div>
);
}

Map / Filter / Reduce

//Map -Create a new array by doing something with each item in an array.

function double(x) {
return x * 2;
}
const newNumbers = numbers.map(double);

//OR

const newNumbers = numbers.map(function (x) {
return x * 2;
});

// Use .forEach
var newNumbers = [];
numbers.forEach(function (x) {
newNumbers.push(x * 2);
});



// console.log(newNumbers);

//Use Filter - Create a new array by keeping the items that return true.

const newNumbers = numbers.filter(function(num) {
return num < 10;
});

// use JS way
var newNumbers = [];
numbers.forEach(function(num) {
if (num < 10) {
newNumbers.push(num);
}
})

//Use Reduce - Accumulate a value by doing something to each item in an array.
var newNumber = numbers.reduce(function (accumulator, currentNumber) {
console.log("accumulator = " + accumulator);
console.log("currentNumber = " + currentNumber);
return accumulator + currentNumber;
})

// use .forEach
var newNumber = 0;
numbers.forEach(function (currentNumber) {
newNumber += currentNumber
})

//Find - find the first item that matches from an array.

const newNumber = numbers.find(function (num) {
return num > 10;
})



//FindIndex - find the index of the first item that matches.

const newNumber = numbers.findIndex(function (num) {
return num > 10;
})


//shorten a string

const newEmojipedia = emojipedia.map(function(emojiEntry) {
return emojiEntry.meaning.substring(0, 100);
});

Short the function code

//Before
const newNumbers = numbers.map(function double(x) {
return x * 2;
});

// delete the function name
// replace "function" with "=>"
// delete { return } if there is only single element to return
// if single input, delete the ()

//After
const newNumbers = numbers.map( x => x * 2);

Conditional Rendering

{/*Ternary Operator*/}
{isLoggedIn ? <h1>Hello</h1> : <Login />}

{/*AND Operator*/}
{currentTime > 12 && <h1>Why are you still working?</h1>}
{/*equals to */}
{currentTime > 12 ? <h1>Why are you still working?</h1> : null}

Hooks

import React, { useState } from "react"; //import useState

function App() {
const [time, setTime] = useState("Get Time"); //set the initial value

function getTime() {
setTime(new Date().toLocaleTimeString()); //set the updated value
}

return (
<div className="container">
<h1>{time}</h1> //render the value
<button onClick={getTime}>Get Time</button> //trigger the change
</div>
);
}

export default App;

// event.preventDefault() is to prevent the next default action.
e.g. on form submit button, it will prevent clear out the form
Destruct Array and Objects
const [honda, tesla] = cars; // destruct the array cars
const {coloursByPopularity: hondacolors, speedStats:hondaspeeds} = honda;
// destruct the object honda, and rename its properties
const [hondaTopColour]=hondacolors;
//destruct the first element of the array hondacolors
const {topSpeed: hondaTopSpeed}=hondaspeeds;
//destruct the first property of the object hondaspeeds
//Or alternatively
const { speedStats: { topSpeed: hondaTopSpeed }} = honda;
const { coloursByPopularity: [hondaTopColour]} = honda;
//Or even shorter
const {speedStats: { topSpeed: hondaTopSpeed },
coloursByPopularity: [hondaTopColour]} = honda;

Complext Hooks Case (Multiple Updates)

import React, { useState } from "react";

function App() {
const [fullName, setFullName] = useState({
fName: "",
lName: ""
}); //set intial value as an object

function handleChange(event) {
const { value, name } = event.target; //destruct the event target

setFullName(prevValue => {
if (name === "fName") {
return {
fName: value,
lName: prevValue.lName //use existing value if it's unchanged
};
} else if (name === "lName") {
return {
fName: prevValue.fName,
lname: value
};
}
});
}
// or if use spread operator, the above code can shorten to:
setFullName(prevValue => ({...prevValue,[name]: value}));
}
return (
<div className="container">
<h1>
Hello {fullName.fName} {fullName.lName} //render the two parts
</h1>
<form>
<input
name="fName"
onChange={handleChange} //use the same function as lname
placeholder="First Name"
value={fullName.fName}
/>
<input
name="lName"
onChange={handleChange}
placeholder="Last Name"
value={fullName.lName}
/>
<button>Submit</button>
</form>
</div>
);
}

export default App;

0 Comments