React
基础知识点 Part1
Destructuring Function Parameters: function use destructuring to capture specific properties as
<named parameters>
The Virtual DOM: it makes webpages easier to manage, detects every node, and only refreshes the updated nodes.
JSX
- Use
className
- Self-Closing Tags:
<img />
,<input />
- Wrap your code in curly braces to treat it like ordinary JavaScript
- Event Listeners:
on
+ event type (e.g.,onClick
) - Conditionals:
if
works outside JSX; inside use ternary operatorx ? y : z
map ()
<li>
needs akey
attribute like<li key="003">
- JSX needs an outermost element like
<div></div>
- Use
React Component
react
,reactDOM
- Function components use
PascalCase
- Render component using
createRoot
&render
fromreact-dom
Project: Click an Animal for a Fun Fact
- Add a title using
createRoot
and ternary operator - Add background using a background variable
- Add an array of images using
for..in
loop andpush
- Add fun facts: use
array [index]
and add event listener, useinnerHTML
to modify content
Authorization Form
- Setup using ternary operator
- Login form using
<form>
with two inputs - Show contact info with ternary operator
- Toggle between views
- Handle submit using event listeners
代码模版
import { createRoot } from 'react-dom/client'
const container = document.getElementById('root')
const root = createRoot(container)
root.render(<Component />)
// COMPONENT
import React from 'react'
import ReactDOM from 'react-dom/client'
function MyComponent() {
return <h1>Hello world</h1>
}
ReactDOM.createRoot(document.getElementById('app')).render(<MyComponent />)
基础知识点 Part2
Components Interacting
- Props are info passed between components
- Props are an object holding component info
- Props are immutable
- Attach functions to elements as event handlers
- Naming:
handleEvent
,onEvent
(e.g.,handleClick
,onClick
)
Hooks
useState
with spread syntax:{...oldObj, newKey: newValue}
useEffect
for dynamic change- Call Hooks only at top level
- Only call Hooks from React functions
- Separate Hooks for separate effects
useState
with arrays/objects- Event Object Properties:
type
,target
,currentTarget
, etc. - Event Object Methods:
preventDefault
,stopPropagation
, etc.
React Programming Patterns
- Split into container (stateful) and presentational (stateless) components
- Presentational = UI only
- Container = data fetching, logic, state
Intermediate Patterns
- Inline styles like
<h1 style={{ color: 'red' }}>Hello</h1>
- Store style in a variable and inject via
style={styles}
- Inline styles like
Routing
createBrowserRouter ()
makes the map<RouterProvider router={router}>
<Route path="/"element={<Home />} />
Route
links path with componentLink
&NavLink
are for navigation- Dynamic Routes:
:title
like<Route path='/articles/:title' />
useParams
gets route param- Nested Routes don’t include parent path
Navigate
redirects when rendereduseNavigate
navigates imperatively- Query Parameters:
?order=DESC
Project: CodeyOverflow Forum
- Divide into parts
- Add props to each part
- Assemble components
- Render it
Project: Passing Thoughts
useState
with array- Add thought:
handleText
,onChange
,handleSubmit
,onSubmit
- Delete thought:
removeThought
,filter
, bind to component - Auto-delete:
useEffect
,setTimeout
, bind deletion
Project: Adopt a Pet!
- Install
react-router-dom
- Create route
- Use nested/index routes
- Use URL params in components
- Replace
<a>
with<Link>
- Add search
- Add 404 for pet details
代码模版
const [currentState, setCurrentState] = useState ();
//input form
export function AddThoughtForm (props) {
const [text, setText] = useState ('');
const handleTextChange = (event) => {
setText (event.target.value);
};
return (
<form className="AddThoughtForm">
<input type="text" value={text} onChange={handleTextChange} />
<input type="submit" value="Add" />
</form>
);
}
//submit + add
const handleSubmit = (event) => {
event.preventDefault ();
const thought = {
id: generateId (),
text: text,
expiresAt: getNewExpirationTime (),
};
props.addThought (thought);
};
//manually delete
const removeThought = (thoughtIdToRemove) => {
setThoughts ((thoughts) =>
thoughts.filter ((thought) => thought.id !== thoughtIdToRemove)
);
};
//router setup
npm install --save react-router-dom@6;
import {
createBrowserRouter,
createRoutesFromElements,
Route,
Link,
NavLink,
RouterProvider,
} from 'react-router-dom';
import About from './About';
import Home from './Home';
const router = createBrowserRouter (
createRoutesFromElements (
<>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</>
)
);
function App () {
return (
<RouterProvider router={router}>
<nav>
<Link to="/">Go to Home</Link>
<NavLink to="/about">Go to About</NavLink>
</nav>
</RouterProvider>
);
}
export default App;
//useParams
import { Link, useParams } from 'react-router-dom';
export default function Article () {
let { title } = useParams ();
return (
<article>
<h1>{title}</h1>
</article>
);
}
//useNavigate
import { useNavigate } from 'react-router-dom';
export const ExampleForm = () => {
const navigate = useNavigate ();
const handleSubmit = (e) => {
e.preventDefault ();
navigate ('/');
};
return <form onSubmit={handleSubmit}>{/* form elements */}</form>;
};
//useSearchParams
import { useSearchParams } from 'react-router-dom';
export const SortedList = () => {
const [searchParams, setSearchParams] = useSearchParams ();
const sortOrder = searchParams.get ('order');
console.log (sortOrder); // "DESC"
};