I’ve decided to go through the React course on Codecademy. To see if I can get a better handle on React.
ReactDOM is the name of the React library, a library in JavaScript.
ReactDOM’s render() method makes JSX appear on the page. The first argument passed into this method should be JSX or evaluate to JSX. Then the second argument selects where the JSX gets appended to.
For example:
ReactDOM.render(<h1>Render me!</h1>, document.getElementById(‘app’));
The Render me! h1 JSX is appended to the element with an ID of ‘app’ [<main id=”app”></main>]
For an example of evaluating-to JSX:
const toDoList = An unordered list with todos
ReactDOM.render(
toDoList,
document.getElementById('app')
);
The variable toDoList resolves to a JSX expression; so that JSX expression will be appended to the element with an id of app
React only updates DOM elements that changed. So if you put the same render twice, it will only render once. The second time would be not a change, so React ignores it.
In React, class becomes className; self-closing tags require the backslash (<br /> needs the /); to get React to process info entered within a JSX element as JavaScript, use curly brackets like here <h1>{2 + 3}</h1>;
You can set attributes with variables, like: height={sideLength}; or with object properties, like: src={pics.panda}
Event Listeners are made by giving JSX elements event listener attributes, like <img onClick={wow} />.
Here are all the event listeners supported by React https://reactjs.org/docs/events.html#supported-events
you CANNOT put an if statement into JSX; So how to do conditionals in JSX?
- You can put the if outside of the JSX
Hey, check out this alcoholic beverage!</h1>);
let message;
if (user.age >= drinkingAge) {
message = (<h1>
} else {
message = (<h1>Hey, check out these earrings I got at Claire’s!</h1>);
}
2. Use the ternary operator
[Review of ternary operator:condition ? exprIfTrue : exprIfFalse;
ex:const beverage = age >= 21 ? "Beer" : "Juice"; If age = 35, the beverage equals "Beer"]
const img = <img src={pics[coinToss()===’heads’ ? ‘kitty’ : ‘doggy’]} />; pics[‘kitty’] will return a picture of a kitty because const pics ={kitty: ‘url-to-kitty-pick’ doggy: ‘url-to-dog-pick}
Ex:
3. use the && operator [true if and only if all operands are true] https://dmitripavlutin.com/javascript-and-or-logical-operators/
Keys
A key is a JSX attribute with the name “key” and a unique value <li key=”li-01″>Example1</li>
List items need keys if (1) the list items have memory from one render to the next; or (2) the list items orders can change from one render to the next
They created a code to automate the creation of unique key values:
Recent Comments