React Cheat Sheet

A quick guide to save your time and effort.

Himali Marasinghe
Aeturnum
8 min readMar 19, 2020

--

As a newbie, sometimes a cheat sheet come in handy when you learn a new framework as you get used to the concepts. I’ve put together a guideline for React with useful code snippets for daily use.

Create React App

JSX and Elements

JSX produce basic syntax for React element.

JSX can be used with valid html tags, and as expressions they can be assigned to variables or can be used conditionally or return from functions.

JSX allows to embed expressions,

In the below example, we declared a variable as name and display inside curly brackets.

JSX tags may contain children,

JSX tags self close if empty:

JSX tag attributes are written in camel case:

Use React

  1. Import React and ReactDOM

2. Render JSX in to DOM element

Components and Props

Components let you split UI in to reusable pieces.

  1. Stateless functional component

2. Stateless functional component with arrow function

3. ES6 class components ( can have states)

  • Always start component name in capital

Here’s how the components are used,

Data can be dynamically passed to components using props. Props is a single object with JSX attributes that every component receives as an argument. Props are immutable, which means they can only be read.

For example, this code renders “Hello, Ann” on the page:

There is a special property called ‘children’ on props object if you want to pass elements / components to other components. It is used to display whatever you include between the opening and closing tags when invoking a component.

Fragments

Fragments provides to return multiple components without adding external element to the DOM. Fragments looks like empty JSX syntax.

Conditional Rendering

  1. Using if statements for rendering

2. Using ternary operator

3. Using logical operator

4. Prevent component from rendering

Lists & Keys

We use map() function to transform array in to list of elements.

Any element that is iterated over with map() function requires a unique key to identify the element. Without keys it becomes more complicated to figure out which elements have changed, added or removed.

Key could be a string that uniquely identifies an element in array among others. Ideally, you would use IDs from your data as keys.

If you don’t have ids with your set of data, you can use the second parameter of .map() function to get each element’s index.Try this as the last resort as this approach is not recommended due to negative impact on performance.

Handling Events

Handling events with React has slightly different syntax compared to HTML.

  • Most event handlers starts with ‘handle’
  • React events are named camelCase like attributes / props
  • With JSX pass a function to the event handler inside curly braces

Passing argument to event handler

In this example id is the row id and the e which represent the React event will be passed as the second argument following id argument.

Passing input value from onChange event

In below example, handleChange event returns a Synthetic Event object which contains the target inputs id, name and current value.

State & Lifecycle

State is simply a pure javascript object which holds component-specific information. Unlike props which get passed from the parent component, state is local and managed within the component.

  1. Declare initial state in constructor

2. Use setState method to modify state. Do not modify state directly.

3. setState with previous state.

4. Lifting state up to share state between components

Often if you need to share state between two or more siblings the solution would be lift your state up. For this, you should transfer your state to a parent component that wrap all the siblings, now from your wrapper just distribute your data down via props.

Component Lifecycle

There are special methods on the component class to run code when a component mount, update and unmount. Below diagram portrays a lifecycle of a component.

  1. constructor : called only once in whole lifecycle, used to setup the initial state of the component or to bind event handler method.

2. getDerivedStateFromProps: invoked before calling render method and is expected to return an object to update the state, or null to update nothing. This method is used when state is dependent on props and to sync state with props change.

3. render: This is the only required method in lifecycle. This get invoked whenever state or props change and re-renders the HTML with new changes.

4. componentDidMount: This is invoked immediately after the component is mounted. This is a good place to make API calls.

5. shouldComponentUpdate: This method returns a boolean value which specifies React whether to re-render or skip rendering component altogether when component’s state or props are updated. By default this method returns true.

6. getSnapshotBeforeUpdate: This method is called before the most recently rendered output is committed to DOM. This method has access to both previous and current props and also state. If this method return any value the same is available in componentDidUpdate method as third parameter. This method is useful in tracking state between current DOM and updated DOM. (Eg. scroll position, text selection )

7. componentDidUpdate: This method is invoked immediately after component is updated ( when props or state changes). This method is not called for the initial render. This is a good place to re-load third party libraries and to compare previous prop/state values with current prop /state values.

8.componentWillUnmount: This method is immediately executed when the component is unmounted or removed from DOM. This method is used to do cleanup related to the component. (Eg. clear user sessions, invalidate timers, cancel network requests)

Forms

In react we have two types of inputs. There are uncontrolled inputs which are like traditional HTML form inputs which we use ref to get form values.

Controlled Inputs

In controlled inputs when form value changes, the component that renders the form saves the value in its state. As in below example, each state mutation has a handler function.

<textarea> tag works similar to input tag using value attribute.

Unlike in HTML <select> tag use a value and not a selected attribute.

You can pass an array to value attribute to have multiple options.

Handling multiple form inputs

When there are multiple form inputs we can handle it by modifying the changeHandler method. Here we add name attribute to each input element so that handler can update state dynamically. The name attribute should be same as the name of state as declared in the constructor.

So this article sums up the main concepts of React with useful code snippets for easy reference. Hope you find this useful.

☕️ Thanks for reading.

--

--