Then edit package.json and add the following lines:
Bootstrapping the React app
JSX
JSX is really React.createElement
Use curly braces to evaluate a javascript expression
You can't use if, or for loops inside JSX, they are not _expressions_
Use map with JSX to render collections
Tip: to avoid many nested parens and curlies, use a variable
Tip: Always remember to include a key property when rendering a collection
IMPORTANT: Your component will likely render without any state the first time
This is the most common problem new React developers run into. When you are fetching remote data, your component will first render with no data. So write your code in your component defensively to avoid this.
Use an empty array as initial state when using map
Use a guard clause to avoid rendering
Sometimes if you have no data, it's better to just render nothing, or a message to the user that the component is "loading".
useState Hook
Defining a piece of state
useState returns an array with two elements, the state itself, and a function to update the state. It accepts the initial value for the state as an argument
the set function only QUEUES an update
If you try to access the state after you've changed it, it won't have changed yet. This is because the set function only queues up a change, it doesn't happen right away.
the set function can optionally take a callback function
Whatever we return from the callback will be the new state. It gets passed the previous state value as the first argument.
useEffect Hook
Components must be PURE functions
They must return JSX or null and not interact with anything outside of the function.
Don't call the set function of useState inside a component
It should always be called in a useEffect or in an event handler.
useEffect takes a callback as it's first argument, and a dependency array as it's second argument
The dependency array
The dependency array decides WHEN the useEffect callback will run.
undefined - The callback will run everytime
[] - The callback will run only on the first render.
[somevariable] - The callback will run on the first render and anytime somevariable changes.
Do use useEffect for side effects
Common side effects we should put in a useEffect Hook:
Fetch Calls
Reading or writing to localStorage
Reading or writing Cookies
Accessing a global variable (you should avoid this anyway)
When to not use useEffect
When you are just doing rendering logic or calculating a value
When you have an event listener like a click or submit
Event Handling in React
Events are added to JSX and passed a callback
In DOM you might do this:
In React you add them using attributes on the JSX
It's cleaner to define your event callback externally to the JSX
Don't call the function in the onClick attribute
useContext Hook
The use context hook is used along with a context to pass data deeply into a React component tree.
context_diagram
Creating a context
Providing data from a component to the context
using the useContext hook
This lets us access whatever we stored in the context's provider's value attribute
Forms
Make your forms controlled components
This means adding an onChange listener to each form control and storing state locally for each control.
Use an onSubmit event on the form tag and remember to prevent default behavior
Using CSS with React
Doing a plain import
This will just add the css file in a <style> tag in the <head> of your HTML.
Using a CSS Module
styles will be an object full of css class names.
You can then use then on your JSX markup as the className.
React will generate random CSS classnames guaranteed to not conflict with styles from other components.
Importing Images
You can import any image file supported on the web: jpg, png, or svg. Then just use it on the src attribute of an image tag.
// Remember the key should be a unique value
const itemComponents = items.map(item =>
<Item key={item.id} item={item}>
);
const [items, setItem] = useState();
// Whoops, we have undefined state ^^^
// We really should use an empty array:
// useState([])
// This generates an error because we can't
// call map on an undefined value of items.
const itemComponents = items.map((item) => {
<Item key={item.id} item={item} />;
});
const MyComponent = () => {
const [items, setItems] = useState([]);
// This is a guard clause, it returns from our
// component early if our items array is empty.
if (items.length === 0) {
return null;
// or you might return a loading message
// return <div>Loading...</div>
}
return (
// Return our normal JSX here.
)
}
const [thing, setThing] = useState(initialState);
const [count, setCount] = useState(0);
// ...later in the component
setCount(count + 1);
console.log(count); // this will still be 0.
// On the next render, count will be 1.
const MyComponent = () => {
const [data, setData] = useState();
// You can't do this! It's a side effect!
fetch(url)
.then((response) => response.json())
.then((data) => setData(data));
};
const MyComponent = () => {
const [message, setMessage] = useState();
setData("Hello World"); // This is a side effect!
// It will actually trigger an endless loop of rendering!
};
useEffect(() => {
// side effect code goes here
}, []); // This is the dependency array
button.addEventListener("click", (event) => {
// Do something with the event.target
});
return (
<button
onClick={(event) => {
// Do something with the event.target
}}
>
Click Me!
</button>
);
const handleClick = (event) => {
// Do something with the event.target
};
return <button onClick={handleClick}>Click Me!</button>;
// This will run the handleClick right away, instead of waiting
// for the click to happen.
return <button onClick={handleClick()}>Click Me!</button>;
import myContext from "./myContext.js";
const AncestorComponent = () => {
// Often we'll use useState or useReducer to store the actual state here
const [message, setMessage] = useState("Hello World");
// Then make an object to assign to the provider's value attribute
const contextValue = {
message,
setMessage,
};
// We are wrapping this around <App> but contexts could
// live at any point in the tree.
return (
<myContext.Provider value={contextValue}>
<App />
</myContext.Provider>
);
};