Skip to main content

Command Palette

Search for a command to run...

[TIL] Hackabull 2023

03/25/23

Updated
[TIL] Hackabull 2023

Error Fix

  1. The server cannot bring Flask API -> shut down other running servers

  2. Unable to load react-bootstrap

    1. npm install react-bootstrap bootstrap

    2.    import {Button, Card} from 'react-bootstrap';
         import 'bootstrap/dist/css/bootstrap.min.css';
      
         // This import below didn't work
         // import Button from 'react-bootstrap/Button';
         // import Card from 'react-bootstrap/Card';
      

requirements.txt in Python

  1. To generate requirements.txt => pip freeze > requirements.txt

  2. To download packages in requirements.txt => pip install -r requirements.txt


React

Installation

  1. npx create-react-app [proj-name]

    1. Download packages for executing the existing React app: npm install
  2. Run React server: npm start

JSX

  1. Embedding Expressions

     const name = 'Josh Perez';
     const element = <h1>Hello, {name}</h1>;
    
  2. className=, not class= in HTML tag & function can only return a single root node

     return (
         <>
             <div className="modal">
                 <h4>title</h4>
                     <p>date</p>
                     <p>details</p>
             </div>
             <div>
                 <p>Hi, it's Siwon</p>
             </div>
         </>
     );
    
  3. Insert style inside the tag

     return ( <h4 style={{ color: "red", fontSize: "16px" }}>title</h4> );
    

State

When the state object changes, the component re-renders

import { useState } from "react";

function Counter() {
    const [count, setCount] = useState(0);
    const onIncrease = () => {
        setCount(count + 1);
    };

    const onDecrease = () => {
        setCount(count - 1);
    };

    return (
        <div>
            <h2>{count}</h2>
            <button onClick={onIncrease}>+</button>
            <button onClick={onDecrease}>-</button>
        </div>
    );
};

export default Counter;
  • Spread Syntax: ...

    • The Spread Syntax is used to deconstruct an array or object into separate variables where the exact number of elements in the array may not be known or when we wish to keep an attribute or a set of attributes separate from the entire object.

    • If we want to change array or object states, we should put this ... syntax because the state is declared as an arrow that is pointing to the value in the buffer. So, if we forget to use spread syntax, nothing is going to be changed.

    • let arr = [1, 2, 3]; => arr stores the arrow pointing to the value in RAM, not the value

    function App() {
        let [title, titleChange] = useState(['t3', 't1', 't2']);
        return (
            <div>
                <button
                    onClick={() => {
                        let orderBy = [...title]; // spread syntax
                        orderBy.sort();
                        titleChange(orderBy);
                    }}
                >
            </div>
        )
    }

Components

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML.

import Counter from "./Counter"; // import Components to App.js

function App() {
    return (
        <>
            <Counter /> // bring Component
        </>
    );
}

Props

Props are arguments passed into React components. Props are passed to components via HTML attributes

import Counter from "./Counter";

function App() {
    const counterProps = {
        a: 1,
        b: 2,
        c: 3,
        initialValue: 4,
    };
    return (
    <>
        <Counter {...counterProps} />
    </>
    );
}

export default App;
import { useState } from "react";

function Counter(props) {
    const [count, setCount] = useState(props.initialValue);
    const onIncrease = () => {
        setCount(count + 1);
    };

    const onDecrease = () => {
        setCount(count - 1);
    };

    return (
        <div>
            <h2>{count}</h2>
            <button onClick={onIncrease}>+</button>
            <button onClick={onDecrease}>-</button>
        </div>
    );
};

Counter.defaultProps = {
    initialValue: 0,
} // we can avoid the error when initialValue is missing in App()

export default Counter;

Container

const Container = ({children}) => {
    return (
        <div style={{ margin: 20, padding: 20, border: '1px solid gray'}}>
            {children}
        </div>
    )
}

export default Container;
import Counter from "./Counter";

function App() {
    return (
    <Container>
        <Counter {...counterProps} />
    </Container>
    );
}

export default App;

useEffect(): fetch API

  1. Add Proxy

    • Without setting a Proxy, it shows an error

  1. useEffect() : bring data only when the webpage is first executed
useEffect(() => {
    fetch("/apt") // GET data from the url (data contained in http://127.0.0.1:5000/apt)
            .then((res) => res.json())
            .then((data) => {
        setApts(data["apt_info"])
        console.log(apts);
      }).catch(
        err => console.log(err)
      )
    }, []);
  • Finalized code

      import '../App.css';
      import { useEffect, useState } from "react";
      import { Button, Card } from 'react-bootstrap';
      import 'bootstrap/dist/css/bootstrap.min.css';
    
      const Cards = () => {
          const [apts, setApts] = useState([{}])
    
          useEffect(() => {
              fetch("/apt")
                  .then((res) => res.json())
                  .then((data) => {
              setApts(data["apt_info"])
              console.log(apts);
            }).catch(
              err => console.log(err)
            )
          }, []);
    
          return (
              <div className="mycards">
                  <div id="cards" className="row row-cols-1 row-cols-md-4 g-4">
                      {apts.map((a) => { 
                         return (
                          <div className="col">
                              <Card style={{ width: '18rem' }}>
                                  <Card.Img className="" variant="top" src={a["image"]} />
                                  <Card.Body>
                                      <Card.Title>{a["name"]}</Card.Title>
                                      <Card.Subtitle className="mb-2 text-muted">{a["address"]}</Card.Subtitle>
                                      <Card.Text>{a["price"]}</Card.Text>
                                      <Card.Text>{a["size"]}</Card.Text>
                                      <Button variant="primary" href={a["link"]} style={{ border: '0px', backgroundColor: '#046648' }}>VISIT</Button>
                                  </Card.Body>
                              </Card>
                          </div>
                         )
                      })}
                  </div>
              </div>
          )
      }
    
      export default Cards;
    

Today I Learned

Part 1 of 50

Today I Learned!