image

React & JSX Quick Reference Guide

Overview

ConceptExample
Basic JSX<div>...</div>
JSX Component<Component property={javascript} />
Component with Children<Component>{children}</Component>
Escaping JavaScript{...}
Importing Reactconst React = require('react');
Importing ReactDOMconst ReactDOM = require('react-dom');
Rendering in the DOMReactDOM.render(<MyApp />, document.getElementById('root'));
Functional Componentfunction MyComponent(props) { return <div>...</div>; }
Base Class for Class ComponentsReact.Component
Constructor's First Statementsuper(props)
Initializing Statethis.state={...}
Updating Statethis.setState({...})
Accessing Previous Statethis.setState(prevState => ({...}))

Functional Component Example

'use strict'; const React = require('react'); function Greeting(props) { return ( <h1>{props.salutation + ' ' + props.who + '!'}</h1> ); } const world = 'world'; <Greeting salutation='hello' who={world} />

Class Component with State

class MyComponent extends React.Component { constructor(props) { super(props); this.state = {property: 'initial'}; this.handleClick = this.handleClick.bind(this); } render() { return ( <div> <button onClick={this.handleClick}>Click me!</button> <div>{this.state.property}</div> </div> ); } handleClick() { this.setState({property: 'clicked'}); } }

Rendering React Component in the DOM

HTML Structure

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>React is awesome!</title> </head> <body> <div id="root"></div> <script src="https://example.com/transformed-with-babel.js"></script> </body> </html>

JavaScript for Rendering

'use strict'; const React = require('react'); const ReactDOM = require('react-dom'); const MyCoolApp = require('./my-cool-app.js'); ReactDOM.render( <MyCoolApp />, document.getElementById('root') );

Component with Children

const borderStyle = { border: '1px solid darkcyan', boxShadow: '5px 5px 5px gray', margin: '10px', padding: '5px' }; function Border(props) { return ( <div style={borderStyle}> {props.children} </div> ); }

Comparison: HTML, Web API, and React JSX

Attribute TypeHTMLWeb APIReact JSX
Attribute/Property Nameslower casemostly camelCasecamelCase
Attribute Valuesstringexpressionexpression within { }
Event Handler Names (on...)lower caselower case (!)camelCase
Event Handler ValuesJavaScript stringfunction expressionfunction expression within { }
Preventing Default Behaviorn/acan return falsemust call event.preventDefault();
HTML Tagslower casen/alower case
Custom Tags (Components)n/an/astart with capital letter

Attribute Examples

HTML AttributeHTML ExampleJSX PropertyJSX Example
class<div class='fancy'>...</div>className*<div className='fancy'>...</div>
onclick<button onclick="foo()">...onClick*<button onClick={foo}>...</button>
tabindex<input tabindex=2 />tabIndex<input tabIndex={2} />

*Note: className matches the Web API, whereas onClick does not! See MDN documentation for further details.

Special Tag Behavior

TagHTML BehaviorReact Behavior
<textarea>content defined by childrencontent defined by value attribute
<select>selection defined by presence of selected attributeselection defined by value attribute on <select>

Inline CSS vs. React Inline Style

AspectInline CSSReact Inline Style
style Attribute/Propertya string enclosed by " or 'an object enclosed by { }
Style Property Nameslower case with hyphen -camelCase
Style Property ValuesCSS expression (textual)JavaScript expression
Separator;,
Merging Stylesnoyes, e.g., with Object.assign()
Variable Usagenoyes

CSS vs. React Style Examples

CSS PropertyCSS Inline Style ExampleReact Style PropertyReact Inline Style Example
background-colorstyle="background-color: green"backgroundColorstyle={{backgroundColor: 'green'}}
borderstyle="border: 1px solid black"borderstyle={{border: '1px solid black'}}
border-style,
border-width
style='border-style: solid; border-width: 5'borderStyle,
borderWidth
style={{borderStyle: 'solid', borderWidth: 5}}

Component Lifecycle Methods

Lifecycle EventMethod
Before Component UnmountscomponentWillUnmount()
After Component MountscomponentDidMount()
Before Component UpdatescomponentWillUpdate(nextProps, nextState)
After Component UpdatescomponentDidUpdate(prevProps, prevState)

Handy Tips

TipDescription
Binding thisUse this.handleEvent.bind(this); in the constructor.
Unique IDs in LoopsUse <button onClick={(e) => this.method(id, e)}>...</button> or <button onClick={this.method.bind(this, id)}>...</button>
Conditional Rendering with &&{condition && <SomeComponent>...</SomeComponent>}
Conditional Rendering with Ternary{condition ? (<TrueComponent>...) : (<FalseComponent>...)}
Prevent RenderingReturn null in the render() method.
Prevent NavigationUse href="#" or <a href="#" onClick={...}>...</a>
Reusing Event HandlersUse a custom name attribute and evaluate it with event.target.name.

Babel Configuration

Preset: react

Manual Transformation Example

const babel = require('babel-core'); let transformed = babel.transform(code, {"presets": ["react"]}).code;

CSS for Full Page

html, body, #root { margin: 0; height: 100%; width: 100%; }

This guide should serve as a handy reference for working with React and JSX, maintaining the core code while ensuring a fresh presentation of the material. Sourced and edit from @delibytes Github Git.