Chenyo's org-static-blog

Posts tagged "react":

23 Jun 2024

Weblab notes: React route

This is a personal note for the web.lab lectures.

1. Router

  • use the Reach Reach Router library
  • URL -> Router -> render different components

    1: <App>
    2:   // conditional rendering based on curren url
    3:   <Router>
    4:     <Home path="/" /> // root path
    5:     <Dashboard path="dashboard" /> // relative to the current URL
    6:     <Team path="/team" /> // absolute path: root path + "/team"
    7:     <NotFound default />
    8:   </Router>
    9: </App>;
    

2. Link

  • relative: <Link to="newpage">Click me</Link>
  • absolute: <Link to="/newpage">Click me</Link>

3. Workshop 3

3.1. Structure

workshop-3-structure.png
Figure 1: The Catbook structure in workshop 3

3.2. States

name states
Feed stories: a list of stories
Card comments: a list of comments for a story id

3.3. Props

index props
1 a function to update stories
2 all attributes in a story
3 the attributes used to display a story
4 a story id; a list of comments under the story; a function to update comments
5 all attributes in a comment
6 a comment id; the function to update comments

3.4. Why passing down the update function in props 1, 4, 6?

  • To share the parent states, i.e., stories and comments to child component. Since the post action happens in the child component, we need a way to automatically update the states to see new contents immediately.
Tags: study web react mit
23 Jun 2024

Weblab notes: React hooks

This is a personal note for the web.lab lectures.

1. What is a React hook

  • Special functions to access parts of the component lifestyle.
  • e.g., useState

1.1. useState is not enough

1: const [persons, setPersons] = useState([]);
2: 
3: testingStuff = () => {
4:     /* assume persons is empty before */
5:     setPersons([...persons, "me"]);
6: }
7: console.log(persons);
  • The output of console.log is [] instead of ["me"] because setting a state is async!
  • To do something immediately after a state is changed, use useEffect hook!

1.2. useEffect runs after specific variable change

1: useEffect(() => {
2:     console.log(persons);
3: }, [persons]);
1: useEffect(() => {
2: /* do something, e.g., interact with an external service */
3: 
4: return () => {
5: /* cleanup function on dismount, e.g., disconnect from external service */
6: }
7: }, [/*dependencies */])
  • useEffect(myFunction, [var1, var2]) calls myFunction everytime when var1 or var2 changes
  • useEffect(myFunction, []]) calls only once when the component is rendered for the first time (on mount)
  • useEffect(myFunction) calls at every render

2. React hook patterns

2.1. Fetch and send data

1: /* fetch data on mount */
2: useEffect(() => {
3:     get("/api/packages").then((packageList) => {
4:         setPackages(packageList);
5:     });
6: }, []);
1: /* send data then toggle admin state */
2: const handleToggleAdmin = () => {
3:     // .then(), do something once the promise is fulfilled
4:     post("/api/user/admin", { admin: !admin }).then(() => {
5:         setAdmin(!admin);
6:     });
7: };
8: /* <Button onClick={handleToggleAdmin} */

2.2. Conditional rendering

1: // JSX is a way of writing HTML in js
2: let content = loading ? <p>Loading...</p> : <p>Loaded</p>;
3: return (
4:     <div>
5:         <h1>Title</h1>
6:         {content}
7:     </div>
8: );

2.3. Render an array of Data

1: const data = [
2:     { id: 0, text: "Text 1" },
3:     { id: 1, text: "Text 2" },
4: ];
5: // render a component for each data item
6: return data.map((item) => (
7:     <ItemComponent key={item.id}>{item.text}</ItemComponent>
8: ));
  • key is a special prop in React; it is used identify which item has changed efficiently

3. Example: Stopwatch

 1: const Stopwatch = () => {
 2:     const [time, setTimer] = useState(0);
 3: 
 4:     useEffect(() => {
 5:         const timer = setInterval(() => {
 6:             // setTimer accepts either a new state value,
 7:             // or a function that takes the previous state (oldTime) as an argument and returns the new state
 8:             setTime((oldTime) => oldTime + 1);}, 1000);
 9:         // if not properly cleanup after unmounting
10:         // the timer will continue to run even the state no longer exists
11:         return () => clearInterval(timer);
12:     }, []);
13:     return <>TIme: {time}</>;
14: };

4. DOM and component mounting

  • DOM (Document Object Model): a programming interface for web documents; represents the structure of a document, e.g., HTML, as a tree of objects, where each object corresponds to a part of the document; it dynamically updates the document contents
    • React is a framework that manipulates DOM
  • A React component is unmounted when:
    • conditional rendering
    • routing; navigating from one route to another
    • its parent component is unmounted
Tags: study web react mit
Other posts