Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@isaklafleur
Last active January 19, 2018 21:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaklafleur/777884ad5919388095ba77ac24bd57b5 to your computer and use it in GitHub Desktop.
Save isaklafleur/777884ad5919388095ba77ac24bd57b5 to your computer and use it in GitHub Desktop.
React Cheat Sheet
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
constructor() {
super();
this.state = {
txt: 'this is the state txt',
};
}
update(event) {
this.setState({ txt: event.target.value });
}
render() {
return (
<div>
<h1>{this.state.txt}</h1>
<Widget update={this.update.bind(this)} />
<Widget update={this.update.bind(this)} />
<Widget update={this.update.bind(this)} />
</div>
);
}
}
App.PropTypes = {
txt: PropTypes.string,
};
const Widget = props =>
<input type="text" onChange={props.update} />;
export default App;
import React from 'react';
class App extends React.Component {
render() {
return <Button>I <Heart /> React</Button>;
}
}
const Button = props => <button>{ props.children }</button>;
class Heart extends React.Component {
render() {
return <span>&hearts;</span>;
}
}
export default App;
import React from 'react';
// This is a "Class Component"
class App extends React.Component {
// Render method is only allowed to return a single node!
render() {
// return <h1 className="big">Hello World!</h1> <b>Bold</b>
return (
<div>
<h1 className="big">Hello World!</h1> <b>Bold</b>
</div>
);
}
}
// This is a "State Less Function Component"
/* const App = () => <h1>Hello World!</h1>; */
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
class App extends React.Component {
constructor() {
super();
this.state = {
red: 0,
};
this.update = this.update.bind(this);
}
update() {
this.setState({
red: ReactDOM.findDOMNode(this.node.refs.red.refs.inp).value,
});
}
render() {
return (
<div>
<NumInput
ref="red"
min={0}
max={255}
step={0.01}
val={+this.state.red}
// type="number"
label="Red"
update={this.update}
/>
</div>
);
}
}
class NumInput extends React.Component {
render() {
let label = this.props.label !== '' ?
<label>{this.props.label} - {this.props.val}</label> : '';
return (
<div>
<input ref="inp"
type={this.props.type}
min={this.props.min}
max={this.props.max}
step={this.props.step}
defaultValue={this.props.val}
onChange={this.props.update}
/>
{label}
</div>
);
}
}
NumInput.propTypes = {
min: PropTypes.number,
max: PropTypes.number,
step: PropTypes.number,
val: PropTypes.number,
label: PropTypes.string,
update: PropTypes.func.isRequired,
type: PropTypes.oneOf(['number', 'range']),
};
NumInput.defaultProps = {
min: 0,
max: 0,
step: 1,
val: 0,
label: '',
type: 'range',
};
export default App;
// Compose React Component Behavior with Higher Order Components
// Higher order components will allow you to apply behaviors
// to multiple React components. This can be done by passing
// the state and any functions into components as props.
import React from 'react';
const HOC = InnerComponent => class extends React.Component {
constructor() {
super();
this.state = { count: 0 };
}
update() {
this.setState({ count: this.state.count + 1 });
}
componentWillMount() {
console.log('will mount');
}
render() {
return (
<InnerComponent
{...this.props}
{...this.state}
update={this.update.bind(this)}
/>
);
}
};
class App extends React.Component {
render() {
return (
<div>
<Button>button</Button>
<hr />
<LabelHOC>label</LabelHOC>
</div>
);
}
}
const Button = HOC(props =>
<button onClick={props.update}>{props.children} - {props.count}</button>);
class Label extends React.Component {
componentWillMount() {
console.log('label will mount');
}
render() {
return (
<label onMouseMove={this.props.update}>{this.props.children} - {this.props.count}</label>
);
}
}
const LabelHOC = HOC(Label);
export default App;
// Control React Component Updates When New Props Are Received
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
class App extends React.Component {
constructor() {
super();
this.state = { increasing: false };
}
update() {
ReactDOM.render(
<App val={this.props.val + 1} />,
document.getElementById('root'));
}
componentWillReceiveProps(nextProps) {
this.setState({ increasing: nextProps.val > this.props.val });
}
shouldComponentUpdate(nextProps, nextState) {
return nextProps.val % 5 === 0;
}
componentDidUpdate(prevProps, prevState) {
console.log(`prevProps: ${prevProps.val}`);
}
render() {
console.log(this.state.increasing);
return (
<button onClick={this.update.bind(this)}>
{this.props.val}
</button>
);
}
}
App.propTypes = {
val: PropTypes.PropTypes.number,
};
App.defaultProps = { val: 0 };
export default App;
// Understand the React Component Lifecycle Methods
// React components have a lifecycle, and you are able
// to access specific phases of that lifecycle.
// This gist gives an overview of the entire component
// lifecycle and demonstrates mounting and unmounting of your
// React components.
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.state = { val: 0 };
this.update = this.update.bind(this);
}
componentWillMount() {
console.log('componentWillMount');
}
componentDidMount() {
console.log('componentDidMount');
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
update() {
this.setState({ val: this.state.val + 1 });
}
render() {
console.log('render');
return <button onClick={this.update}>{this.state.val}</button>;
}
}
class Wrapper extends React.Component {
mount() {
ReactDOM.render(<App />, document.getElementById('a'));
}
unmount() {
ReactDOM.unmountComponentAtNode(document.getElementById('a'));
}
render() {
return (
<div>
<button onClick={this.mount.bind(this)}>Mount</button>
<button onClick={this.unmount.bind(this)}>UnMount</button>
<div id="a"></div>
</div>
);
}
}
export default Wrapper;
// Manage React Component State with Lifecycle Methods
// explains_lifecycle_methods.jsx introduced the React
// component lifecycle mounting and unmounting.
// Here I explaine some simple uses for these hooks
// and how we can interact with state.
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.state = { val: 0 };
this.update = this.update.bind(this);
}
componentWillMount() {
console.log('componentWillMount');
this.setState({ m: 2 });
}
componentDidMount() {
console.log('componentDidMount');
// console.log(ReactDOM.findDOMNode(this));
this.inc = setInterval(this.update, 500);
}
componentWillUnmount() {
console.log('componentWillUnmount');
clearInterval(this.inc);
}
update() {
this.setState({ val: this.state.val + 1 });
}
render() {
console.log('render');
// console.log(this.state);
return (
<button onClick={this.update}>
{this.state.val * this.state.m}
</button>
);
}
}
class Wrapper extends React.Component {
mount() {
ReactDOM.render(<App />, document.getElementById('a'));
}
unmount() {
ReactDOM.unmountComponentAtNode(document.getElementById('a'));
}
render() {
return (
<div>
<button onClick={this.mount.bind(this)}>Mount</button>
<button onClick={this.unmount.bind(this)}>UnMount</button>
<div id="a"></div>
</div>
);
}
}
export default Wrapper;
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
render() {
const txt = this.props.txt;
const cat = this.props.cat;
return <h1>{txt} {cat}</h1>;
}
}
App.propTypes = {
txt: PropTypes.PropTypes.string,
cat: PropTypes.PropTypes.number.isRequired,
};
App.defaultProps = {
txt: 'this is the default txt',
};
export default App;
// Add Custom propType Validation to React Components
// In addition to the types built into React.propTypes we can also define our own custom propType validator
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
render() {
return <Title text1="testing to fill in some text in text1" text2="123456" />;
}
}
const Title = props => <h1>Title: { props.text1 } - { props.text2 }</h1>;
// Defining the props... isRequired mean that the prop need to have a value
Title.propTypes = {
text1: PropTypes.string.isRequired,
text2(props, propName) {
if (!(propName in props)) {
return new Error(`missing ${propName}`);
}
if (props[propName].length < 6) {
return new Error(`${propName} was too short`);
}
},
};
export default App;
// ts with Reacts Synthetic Event System
// Event handlers are passed an instance of SyntheticEvent
// in React. We'll take a look at the wide range of events available to us,
// including Touch events.
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
constructor() {
super();
this.state = { currentEvent: '-----' };
this.update = this.update.bind(this);
}
update(event) {
this.setState({ currentEvent: event.type });
}
render() {
return (
<div>
<textarea
onKeyPress={this.update}
onCopy={this.update}
onCut={this.update}
onPaste={this.update}
onFocus={this.update}
onBlur={this.update}
onDoubleClick={this.update}
onTouchStart={this.update}
onTouchMove={this.update}
onTouchEnd={this.update}
cols="30"
rows="10"
/>
<h1>{this.state.currentEvent}</h1>
</div>
);
}
}
App.PropTypes = {
};
export default App;
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
txt: 'this is the state txt',
cat: 0,
};
}
update(event) {
this.setState({ txt: event.target.value });
}
render() {
return (
<div>
<input
type="text"
onChange={this.update.bind(this)}
/>
<h1>{this.state.txt} - {this.state.cat}</h1>
</div>
);
}
}
export default App;
// Use React ref to Get a Reference to Specific Components
// When you are using React components you need to be able
// to access specific references to individual component
// instances. This is done by defining a ref.
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.state = { a: '' };
}
update() {
this.setState({
a: this.a.refs.input.value,
b: this.b.value,
});
}
render() {
return (
<div>
<Input
ref={(component) => { this.a = component; }}
update={this.update.bind(this)}
/> {this.state.a}
<hr />
<input
ref={(node) => { this.b = node; }}
type="text"
onChange={this.update.bind(this)}
/> {this.state.b}
</div>
);
}
}
class Input extends React.Component {
render() {
return <div><input ref="input" type="text" onChange={this.props.update} /></div>;
}
}
export default App;
<!DOCTYPE html>
<html lang="en">
<head>
<title>React App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="root"></div>
</body>
</html>
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
//
ReactDOM.render(
<App cat={5} txt="this is the prop text2" />,
document.getElementById('root'),
);
import React from 'react';
class App extends React.Component {
render() {
return (
<Parent>
<div className="childA"></div>
{/*<div className="childB"></div>*/}
{/*<div className="childC"></div>*/}
</Parent>
);
}
}
class Parent extends React.Component {
render() {
// console.log(this.props.children);
let items1 = React.Children.map(this.props.children, child => child);
let items3 = React.Children.toArray(this.props.children)
let items2 = React.Children.forEach(this.props.children, child => console.log(child.props.className));
let items4 = React.Children.only(this.props.children);
console.log('.forEach: ', items2);
console.log('.map: ', items1);
console.log('.map short-handed: ', items3);
console.log('.only: ', items4); // only works with single React Element child.
return null;
}
}
export default App;
// Use map to Create React Components from Arrays of Data
// React components can be dynamically generated based on
// a dataset. Here I show how to do just that by mapping over
// the state.data object.
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { items: [] };
}
componentWillMount() {
fetch('http://swapi.co/api/people/?format=json')
.then(response => response.json())
.then(({ results: items }) => this.setState({ items }));
}
// filter method
filter(e) {
this.setState({ filter: e.target.value });
}
render() {
let items = this.state.items;
if (this.state.filter) {
items = items.filter(item =>
item.name.toLowerCase()
.includes(this.state.filter.toLowerCase()));
}
return (
// 1. add a field that uses the filter method
// 2. map over the array and list the names from the API
<div>
<input type="text" onChange={this.filter.bind(this)} />
{items.map(item =>
<Person key={item.name} person={item} />)}
</div>
);
}
}
const Person = props => <h4>{props.person.name}</h4>;
export default App;
// Use React.cloneElement to Extend Functionality of Children Components
// We can utilize React.cloneElement in order to create
// new components with extended data or functionality.
import React from 'react';
class App extends React.Component {
render() {
return (
<Buttons>
<button value="A">A</button>
<button value="B">B</button>
<button value="C">C</button>
</Buttons>
);
}
}
class Buttons extends React.Component {
constructor() {
super();
this.state = { selected: 'None' };
}
selectItem(selected) {
this.setState({ selected });
}
render() {
let fn = child =>
React.cloneElement(child, { onClick: this.selectItem.bind(this, child.props.value),
});
let items = React.Children.map(this.props.children, fn);
return (
<div>
<h2>You have Selected: {this.state.selected}</h2>
{items}
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment