Posts tagged "web":
15 Aug 2024
Web learning in practice
This post records the basic web development knowledge I have learned in practice.
1. Basic html structure
<!DOCTYPE html> <html lang="en"> <!-- A head --> <head> <meta charset="UTF-8"> <!-- to accommodate different screen size --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- A tab name --> <title>A website</title> <link rel="stylesheet" href="styles.css"> </head> <!-- A body --> <<body> <!-- A page header --> <header> <h1>Welcome</h1> </header> <!-- A navigation panel --> <nav> <ul> <<li><a href="index.html">Home</a></li> </ul> </nav> <!-- The main content --> <main> <section id="home"> <h2>Home</h2> <p>Welcome!</p> </section> </main> <!-- A footer --> <footer> <p>© All rights reserved.</p> </footer> </body> </html>
2. Tags
<a>
: contain links; have following attributes:target="_blank"
: open the link in a new tab.title="Go to the link"
: the tooltip message, i.e., the floating message when a user hovers over.
<span>
: don’t add line breaks before or after it.<hr>
: horizontal rule.
3. Attributes
id="home"
:- allow specific styling of the element, e.g.,
#home ul {...}
only styles theul
in the block with the same id.
- allow specific styling of the element, e.g.,
4. Javascript
4.1. Fetch from an HTML URL
await fetch(url)
: returns aResponse
object.await
waits for the method to complete.
await response.text()
: returns thehtml
string.DOMParser().parseFromString(postHtml, "text/html")
: returns aDocument
object, which is a complete DOM tree from the HTML string;DOMParser
is a built-in browser API.postDoc.getElementById("content")
: returns anElement
with thecontent
id name.content.querySelector(".post-title a")
: fetches the firstElement
with thepost-title
class name, and returns the firstElement
the first<a>
(anchor) tag..
for classes,#
for IDs (IDs should be unique within a page)
4.2. Modify a DOM
content.querySelector(".taglist").remove()
: removes the element from the DOM, i.e., it modifiescontent
.
4.3. Syntax
const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
: add a backslash to any special character in the query;$&
is a special pattern used in Javascript’sreplacement
method.
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
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
andcomments
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.
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])
callsmyFunction
everytime whenvar1
orvar2
changesuseEffect(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