TIL - Styling and Handling Events in React Components

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){
event.persist(); // MUST INCLUDE THIS!
this.setState(() => {
searchTerm: event.target.value
});
setTimeout(function(){
console.log('event', event);
console.log('event.target', event.target);
}, 500)
}

You also need to bind event handlers to the class, or they won’t work!

constructor(props){
super(props);
this.state = {
searchTerm: ''
}
this.handler = this.handler.bind(this);
}

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 as onClick={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}) {
console.log('rendering a car', car);
return (
<li>{car.name} (bhp: {car.bhp})</li>
);
}

// instead of

function Car(props) {
console.log('rendering a car', props.car);
return (
<li>{props.car.name} (bhp: {props.car.bhp})</li>
);
}

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 the cuid() browser method to set unique keys, or UUID in Node apps.