TIL - Styling and Handling Events in React Components
January 25, 2020
What follows is notes from a class. Incomplete thoughts & code that probably will only make sense to me. Given enough time, even that may be a stretch! Reference at your own risk 😂
Slides
Styling Components 3 Ways - CodePen pen
Handling Events
See CodePen example to illustrate the below points.
Events in React components are synthetic events and may not always act the way they would in normal JS. Notably, they are asynchronous.
React is always trying to free up memory; one way it does this is to nullify events when they happen. To avoid this you need to call event.persist()
if you need to use data that comes from the event.
handler(event){ |
You also need to bind event handlers to the class, or they won’t work!
constructor(props){ |
Other React Things
I’m also reading through the React docs to generally familiarize myself…here are some things I learned that I found interesting/surprising/worth trying extra hard to remember:
- React treats components starting with lowercase letters as DOM tags. For example,
<div />
represents an HTML div tag, but<Welcome />
represents a component and requires Welcome to be in scope. - In events you must always explicitly call
preventDefault
to prevent default responses. - Binding component methods is super important! Generally, if you refer to a method without
()
after it, such asonClick={this.handleClick}
, you should bind that method. - You can build collections of React elements with looping functions! Demo here
- In React, a
<textarea>
uses a value attribute instead of having the text between tags. - You can make placeholders in React components using
{props.children}
(see example). - You can also pass props straight through a component to its children using the spread operator (see example)…this is called prop drilling.
import SubComponent from './components/child/child.js';
function MyComponent(props) {
return (
<div>
<SubComponent ...props />
</div>
);
} - Use destructuring to have to write
props
less (pen):
function Car({car}) { |
Some gotchas I can see might be frequent:
- Binding methods to components in their constructors
- Adding a
key
where they’re necessary and not using the index as a key (“A good rule of thumb is that elements inside the map() call need keys.”) You can use thecuid()
browser method to set unique keys, or UUID in Node apps.