REACT

JSX (JavaScript XML) is an extension to JavaScript syntax used in React. It allows you to write HTML-like code within JavaScript, making it easier to create and manipulate the structure of user interfaces.

JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import React from "react";
import ReactDOM from"react-dom";

//ReactDOM.render(WHAT TO SHOW, WHERE TO SHOW)
ReactDOM.render(<h1>helloworld</h1>, document.getElementById("root"));
// render method can only take one html element




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

ReactDOM.render(
<div>
<h1>haha</h1>
<ul>
<li>bacon</li>
<li>potato</li>
<li>noodles</li>
</ul>
</div>
,document.getElementById("root"));

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<title>JSX</title>
<link rel="stylesheet" href="styles.css" />
</head>

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

tags like image or link are self closing

JSX

JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript.

It’s typically used with React

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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

const name = "Dan";

const num = 12 ;

ReactDOM.render(
<div>
<h1>Hello {name}!</h1>
<p>my lucky number is{ Math.floor( Math.random() * 10 )}</p>
</div>
, document.getElementById("root")//where to show
);

  • ReactDOM.render() is the entry point into the React application. It takes two arguments:
  1. The React element or component that you want to render.
  2. The DOM element where you want to render the React component.
  • in JSX, each expression must have a single outermost parent element. This means that when you’re writing JSX, you need to wrap your JSX elements in a single parent element. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// This is valid JSX
const element = (
<div>
<h1>Hello, world!</h1>
<p>This is a paragraph.</p>
</div>
);

// This is NOT valid JSX
const element = (
<h1>Hello, world!</h1>
<p>This is a paragraph.</p>
);

expression vs. statement

Expressions give you values, while statements do something or control how your code runs.

Expressions in JavaScript produce values. They can be simple, like variables or numbers, or more complex, involving operators or function calls.

Statements in JavaScript perform actions or control the flow of execution. They don’t produce values and consist of keywords, operators, and expressions.

ES6: template literal

image-20240404131756522

image-20240404150203504

  1. **{} (Curly Braces in JSX): **

    • Used within JSX syntax in React or other libraries/frameworks that utilize JSX.
    • Used to embed JavaScript expressions or variables within JSX elements.
    • Allows dynamic values or JavaScript code to be included inside JSX elements.
      Examples:
    1
    2
    const name = "John"; 
    const greeting = <h1>Hello, {name}!</h1>;
  2. ${} (Template Literal Syntax):

    • Used in regular JavaScript outside of JSX syntax.
    • Used specifically within template literals (or template strings).
    • Allows for string interpolation, enabling the embedding of expressions or variables within a string.
1
2
 codeconst name = "John";
const greeting = `Hello, ${name}!`;

In the above code, the variable name is interpolated within the template literal using ${}. The value of name is inserted into the resulting string.

To summarize, {} is used in JSX to embed JavaScript expressions within JSX elements, whereas ${} is used in regular JavaScript as part of template literals to interpolate expressions or variables within strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import React from "react";
import ReactDOM from "react-dom";

const name = "Dan";
const f = "xiang";
const num = 12 ;

ReactDOM.render(
<div>
<h1>Hello {name + " " + f}!</h2> // !
</div>
, document.getElementById("root"));



import React from "react";
import ReactDOM from "react-dom";
const YOURNAME = "Dan"
const CURRENTYEAR = new Date().getFullYear();
ReactDOM.render(
<p>{`${YOURNAME} ${CURRENTYEAR}`} </p>
, document.getElementById("root")
);

HTML Global Attributes

1
<h1 className="heading" contentEditable="true">

contentEditable is a global attribute

JSX Attributes & Styling React Elements

https://codesandbox.io/s/jsx-attributes-and-styling-kkycr?fontsize=14

inline styling:

https://codesandbox.io/s/inline-styling-in-jsx-159y7?fontsize=14

1
2
3
4
5
6
7
8
ReactDOM.render(
<div>
<h1 style={{color: "red"}}>
My Favourite Foods
</h1>
</div>,
document.getElementById("root")
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const customStyle = {
color: "red",
fontSize: "20px",
border:"1px solid black"
}

customStyle.color = "blue";

ReactDOM.render(
<div>
<h1 style={customStyle}>
My Favourite Foods
</h1>
</div>,
document.getElementById("root")
);

https://codesandbox.io/s/react-styling-practice-xpn8u?fontsize=14 (time greeting application)

react components

  • how to structure your code and make it look cleaner?

Airbnb Style Guide for React

  • split off coding into a separate file:

https://codesandbox.io/s/react-components-j66pt?fontsize=14

If Time is a function and you want to export the result of calling that function, you should include parentheses to call it, like Time(). If Time is a variable holding a value, you don’t need parentheses.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//notice: capitalize the first character
import React from "react";
const date = new Date();
const currentTime = date.getHours();
let greeting;
const customStyle = {
color: ""
};
function Time(){
if (currentTime < 12) {
greeting = "Good Morning";
customStyle.color = "red";
} else if (currentTime < 18) {
greeting = "Good Afternoon";
customStyle.color = "green";
} else {
greeting = "Good Night";
customStyle.color = "blue";
}

return <h1 style={customStyle}>{greeting}</h1>;
}
export default Time; // notice: heres no parenthesis

////////////////////////////////////////////////////////////////////////
index.js:

import React from "react";
import ReactDOM from "react-dom";
import Time from "./component/Time"
ReactDOM.render(
<Time/>,
document.getElementById("root")
);

Import , Export, Module

index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React from "react";
import ReactDOM from "react-dom";
import PI from "./math.js"; // will just look for the default export in math.js file, the name(PI), doesn't matter here
//but doublePi, triplePi need to be the exact name with the export statemenet

import pi, { doublePi, triplePi } from "./math.js";
// name { doublePi, triplePi } matters here, you need to call the same name as in the export statement

// you can also say: import pi; beasue pi is default export
import * as pi;from "./math.js";
// you can also say: import * as pi; (import all) ->pi.default pi.doublePi pi.tripleOie()
//wild card(the line above) import is discouraged

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

math.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
// export multiple things at once
const pi = 3.1415962;

function doublePi() {
return pi * 2;
}

function triplePi() {
return pi * 3;
}

export default pi; // can only be one default export per file
export { doublePi, triplePi }; // no parenthesis!

DevTools

https://codesandbox.io/p/sandbox/react-devtools-forked-3j2rvp?file=%2Fsrc%2Fcomponents%2FAvatar.jsx%3A5%2C8

Map function

image-20240406090244506

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import React from "react";
import Card from "./Card";
import contacts from "../contacts";
import Avator from "./Avatar"

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

function App() {
return (
<div>
<h1 className="heading">My Contacts</h1>

{contacts.map(createCard)}

{/* <Card
name={contacts[0].name}
img={contacts[0].imgURL}
tel={contacts[0].phone}
email={contacts[0].email}
/>
<Card
name={contacts[1].name}
img={contacts[1].imgURL}
tel={contacts[1].phone}
email={contacts[1].email}
/>
<Card
name={contacts[2].name}
img={contacts[2].imgURL}
tel={contacts[2].phone}
email={contacts[2].email}
/> */}
</div>
);
}

export default App;

Key property

In React, when you use map to render a list of components, it’s essential to assign a unique identifier to each component. This unique identifier is known as a “key.” The purpose of the key is to help React identify which items have changed, are added, or are removed from the list. React uses these keys to optimize rendering performance and to efficiently update the DOM.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function App() {
return (
<div>
{contacts.map((contact) => (
<Card
key={contact.id} // Using a unique identifier as the key
name={contact.name}
img={contact.imgURL}
tel={contact.phone}
email={contact.email}
/>
))}
</div>
);
}

image-20240406092743047

but you cant use key in card function:

card.jsx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from "react";
import Avatar from "./Avatar";
function Card(props) {
return (
<div className="card">
<div className="top">
<p className="info">{props.key} !</p> # this will not display
<p className="info">{props.id} !</p> # this will display
<h2 className="name">{props.name}</h2>
<Avatar img = {props.imgg} />
</div>
<div className="bottom">
<p className="info">{props.tel}</p>
<p className="info">{props.email}</p>
</div>
</div>
);
}

export default Card;

app.jsx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React from "react";
import Card from "./Card";
import contacts from "../contacts";
import Avator from "./Avatar"

function createCard(contact) {
return <Card
key = {contact.id} # not for us to use
id = {contact.id}
name={contact.name}
imgg={contact.imgURL}
tel={contact.phone}
email={contact.email}
/>;
}

function App() {
return (
<div>
<h1 className="heading">My Contacts</h1>

{contacts.map(createCard)}

</div>
);
}

export default App;

React Hooks

  1. Only call Hooks at the top level: Don’t call Hooks inside loops, conditions, or nested functions. Always use Hooks at the top level of your React functional component or custom Hook. This ensures that Hooks are called in the same order every time a component renders.
  2. Only call Hooks from React functions: You can’t call Hooks from regular JavaScript functions. Hooks should only be called from within React function components or custom Hooks.

https://codesandbox.io/p/sandbox/usestate-hook-completed-ylxqj

what’s hook?
In React, a Hook is a special function that allows you to “hook into” React state and lifecycle features from functional components. Before the introduction of Hooks in React 16.8, state and lifecycle methods were only available in class components. With Hooks, you can use state and other React features in functional components without the need for classes.

Hooks are functions provided by React that you can use to add state and other React features to your functional components. They allow you to reuse stateful logic across multiple components without changing the component hierarchy.

Some commonly used React Hooks include:

  1. useState: Allows functional components to use state.
  2. useEffect: Allows functional components to perform side effects (such as data fetching, DOM manipulation) after the component renders.
  3. useContext: Allows functional components to consume context provided by a Context.Provider higher up in the component tree.
  4. useReducer: An alternative to useState for managing more complex state logic with reducers.
  5. useCallback and useMemo: Optimization Hooks for performance optimization by memoizing functions or values to prevent unnecessary re-renders.
  6. useRef: Allows functional components to persist values across renders without causing re-renders.