Joshua's Cheatsheets-React / JSX - Cheatsheet
Light
help

Other resources

What & Link Type
"The React Handbook" by Flavio Copes - Online version PDF signup
   ---> Amazing resource!
Guide
"React for Vue Developers" by Sebastian De Deyne Guide / Cheatsheet
React Lifecycles Method Diagram Cheatsheet
React+TypeScript Cheatsheets Cheatsheet
PluralSight: Composing React Components with TypeScript Guide
Post: "You Probably Don't Need Derived State" Guide
Collection: enaqx/awesome-react Collection

Binding template literal

Binding template literal to property expecting string: You have to use double brackets to "break out" of JSX and into regular JS. Instead of:

<SEO title="`${props.pageContext.slug}`" />

You need:

<SEO title={`${props.pageContext.slug}`} />

Creating unique keys

You want a unique identifier, which is actually harder than one might expect to create. Using the index provided within a loop is not recommended, and even combining with something like (new Date()).getTime() is not guaranteed to be unique.

There are tons of packages out there that you can drop in to create unique Ids. Or just make a composite key out of enough unique parameters to ensure non-duplicates.

Misc / How Do I...

  • You can now use empty elements, known as fragments, to wrap siblings:

    • <><div></div><div></div></>
  • Issues returning JSX?

    • More than one line? Make sure wrapped in parenthesis return (<div></div>)
    • Make sure there is *only one* root level element
  • Pass a bunch of options to a component as props (basically convert JS Obj to props)

    • Just use spread operator - {...this.props}
  • Simulate a change event on a <input> element

  • How to add an external stylesheet (not for bundling)

    • Instead of using import within a JS file (like App.js), add the stylesheet directly as a link tag element in the HTML file (e.g. <link rel="stylesheet" href="https://.../style.css" />)
  • How do I access an element directly (similar to native browser APIs like document.getElementById) in React? How do I get the DOM node?

    • That is a great use case for React refs! - Docs
    • Options:

      • Newest and recommended: useRef hook

        • myRef = useRef(null)
      • Older:- this.myRef = React.createRef() in class constructor
    • You can access DOM node through myRef.current, after attaching via <MyElement ref={myRef}/>

Tips

  • You can assign JSX to variables! Makes it very easy to reuse!
  • Make use of object destructuring assignments to avoid repetitive props syntax

    • const {hidden, dataArr, isAdmin, isAuthed} = this.props
    • -> Or, destructure right in function argument, const myComponent = ({hidden, dataArr, isAdmin, isAuthed}) => {}
  • You can use class members and/or regular vars to hold changing values, as opposed to putting in state/props, if you want to avoid unnecessary renders when those values are not part of UI

Asset management and usage

You have two main options when it comes to asset management:

  • Public Folder: Place in /public

    • Pull into HTML with %PUBLIC_URL%
    • Pull into JS with process.env.PUBLIC_URL
  • Bundling: Place asset files alongside JS, in /src

    • Pull into JS by using import at top of file with relatively path
    • Pull into css (e.g. for background image) with relative path

The second option is always preferred, since it uses webpack to bundle assets and will help keep the size of your app down by only bundling assets that are actually used (as well as some other tricks).

Importing assets in JS or CSS

Examples:

JS:

import background from './assets/background.jpg';
// ...
render() {
	return (
		<img src={background} />
	)
}

CSS:

#main {
	background-image: url(./assets/background.jpg);
}

Getting around method binding of this

A common issue with React is preserving the value of this, especially when it comes to event handlers, like onClick.

If the callback you are assigning uses this within its body, you will have issues if the value of this changes (most often in a Cannot read property '___' of undefined error).

Here are some ways to ensure the value of this stays the way you want it to:

Explicit, with .bind() on the attribute

The older method was commonly to use .bind() to explicitly bind the value of this at the point of attaching the handler. That might look something like this:

<CustomComponent onClick={this.handleEvent.bind(this)}>

ES6 Class binding

If you are using the new ES6 class syntax, you have all the other options, plus a few more. Let's say this is our base code:

class MyComponent extends React.Component {
	constructor(props) {
		super(props);
		this.state = {counter: 0};
	}

	handleClick(evt) {
		const updatedCount = this.state.counter + 1;
		this.setState({
			counter: updatedCount
		});
		console.log(this.state.counter);
	}

	render() {
		return (
			<button onClick={this.handleClick}> Counter + </button>
		);
	}
}

One option is to use .bind(), in the constructor:

constructor(props) {
	super(props);
	this.state = {counter: 0};
	// ADDED:
	this.handleClick = this.handleClick.bind(this);
}

Another option is to turn the handleClick method, into a member, that is the value of an arrow function, thus automatically binding this to the class:

// Rest of class definition
// Or: public handleClick = (evt) => {}
handleClick = (evt) => {
	const updatedCount = this.state.counter + 1;
	this.setState({
		counter: updatedCount
	});
	console.log(this.state.counter);
}
// ...

Technically, this is actually an ES6 public field, which is, as of 2019, in an experimental stage, so while it is well supported with transpiled JS/TS, it has limited native browser support.

Inline arrow functions

One of the benefits (or drawbacks) of arrow functions is that they lexically bind this - automatically. So, if you do:

<CustomComponent onClick={(evt) => {
	this.handleEvent(evt);
}}>

It doesn't matter if CustomComponent has a different this scope, because the arrow function binds the callback where you defined it!

Use createReactClass

If you use createReactClass, you generally don't have to worry about this issue, as createReactClass uses autobinding, which basically does .bind() for you.

More reading


Computed properties

Unlike Vue, which has a specific syntax for computed properties, React doesn't really care how you try to formulate values based on computed state properties.

ES6 Class - Getter

With the new ES6 class based approach, a very clean solution is to use getters, with something like:

class MyComponent extends React.Component {
	// ... class stuff
	get isAdult() {
		return typeof(this.state.age) === 'number' && this.state.age > 18;
	}
}

Within the render function itself

There is nothing preventing you from computing a value within the render function itself. For example:

class MyComponent extends React.Component {
	// ... class stuff
	render() {
		const isAdult = typeof(this.state.age) === 'number' && this.state.age > 18;
		return (
			<div>
				Is adult = {isAdult.toString()}
			</div>
		);
	}
}

As a function

Another vanilla solution here is to simply use a function to return the computed value, rather than anything else. How you declare this is up to you:

  • Explicitly, with function myFunction(){}
  • As a ES6 class member

    • public isAdult() {}
  • With an arrow function to bind this

    • const isAdult = () => {};
  • Etc.

To use within your render method, simply make sure you actually execute it by following it with the parenthesis and arguments if applicable.

State management system

If you are using a dedicated state management system, there is a chance that what you are using might already have something in place to not only provide explicit computed properties, but also optimize them, to prevent redundant expensive re-calculations.

For example, if you use MobX, make sure to check out this page on computed values.

Further reading:


Handlebars / Mustache type logic (loops, conditional, etc)

Conditional rendering

Tons of options - see "7 ways to implement conditional rendering".

Some tricky ones to remember, but can be very helpful are:

  • AND (&&) operator to show or hide

    • You can use {shouldShowBool && <div>I'll only show up if shouldShowBool is true!</div>}
    • This works because in JS, A && B returns B if A is true, without coercing B to a boolean
  • Ternary Operator (_?_:_) to swap between things

    • You can use {isLeaving ? <p>Goodbye!</p> : <p>Hello!</p>}

Loop / array render

There are a bunch of options. You can:

  • Create an array of JSX template code assigned to a variable, and use it within render(), with something like: items.push(<div key={UNIQUE_KEY}>{CONTENT}</div>);
  • Iterate over the items directly in render(), and return the template there:

    const render = function() {
    	const items = ['bread', 'milk', 'cookies'];
    	return (
    		<ul>
    			{items.map((value, index) => {
    				return <li key={index}>{value}</li>
    			})}
    		</ul>
    	);
    }

React Hooks

What are React Hooks?

React hooks partially came about because of, and an alternative to, the complexity and boilerplate involved with class based components (as opposed to functions) and/or HOCs (higher order components). They are not required to be used, but many new devs prefer them for readability and isolation.

At their core, the key value proposition of React hooks is that they allow you to hook more directly into the React lifecycle and core APIs, such as state, props, etc.

Built-In React Hooks

Hook What
useState Get and set state
useEffect Wrap a function that contains possibly effectful code, which will be called after render.

You can conditionally trigger it by passing a dependency array as the second argument.

You can use it as a cleanup method (before component unmounts), by returning a cleanup function.
useContext Returns the current value for a given context object (object from React.createContext). Value is from nearest Provider.

A context value change will always trigger a re-render.

Using this with a context provider is a common alternative to prop-drilling, and/or large global state management systems.
useReducer An alternative to useState that basically takes a function to mutate state, rather than the state update directly.
useCallback Meant for optimization, you pass a callback and the dependencies that the callback uses to produce a result, and you get back a memoized (i.e. cached) callback function that only changes if the dependencies change.
useMemo Close to useCallback, but returns a memoized value, rather than a callback, that is only recomputed if the dependencies change.
useRef Returns a special mutable reference object, which can be updated, but persists across re-renders and does not trigger re-renders on change.

Value can be accessed with .current.
useImperativeHandle Lets you modify the reference that is passed to parent components (for example, to add a method onto ref.current). If used, should be combined with forwardRef, but also not recommended, period.
useLayoutEffect Essentially the same as useEffect, but fires after all DOM updates have occurred (e.g. at componentDidMount, or componentDidUpdate)
useDebugValue For custom hooks, you can use this to display a special label for the hook inside the React DevTools.
Markdown Source Last Updated:
Mon Mar 23 2020 05:10:49 GMT+0000 (Coordinated Universal Time)
Markdown Source Created:
Wed Aug 21 2019 20:31:01 GMT+0000 (Coordinated Universal Time)
© 2020 Joshua Tzucker, Built with Gatsby