Skip to content

Instantly share code, notes, and snippets.

@jooeycheng
Last active June 24, 2020 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jooeycheng/d9beef2b94385878ac748a7cfe5c5550 to your computer and use it in GitHub Desktop.
Save jooeycheng/d9beef2b94385878ac748a7cfe5c5550 to your computer and use it in GitHub Desktop.
Example React Component (cheatsheet)
/**
* Sample Component file for reference, because Joey forgets simple stuff.
*/
import React from 'react';
import './Sample.scss';
class Sample extends React.Component {
constructor(props) {
super(props);
this.state = {
stateVar: 'foo'
};
this.handleEvent = this.handleEvent.bind(this); // bind custom functions
this.props.propName // access prop variables
this.state.stateVar // access state variables
this.exampleRef = React.createRef(); // create reference to HTML object in DOM
}
/**
* (custom method)
* To access this class' internal `this`, all custom functions must bind in constructor with:
* this.handleEvent = this.handleEvent.bind(this);
*/
handleEvent(e) {
e.preventDefault(); // must be called explicitly to prevent default behavior
}
/**
* (lifecycle method)
* Runs after the component output has been rendered to the DOM
*/
componentDidMount() {
/**
* Update `state` variables
*/
this.setState({ stateVar: 'foo' }) // normal
this.setState(state => ({ stateVar: 'foo' })); // with callback
let container = this.exampleRef.current; // retrieve the node with .current
}
/**
* (lifecycle method)
* Runs after the component removed from DOM
*/
componentWillUnmount() {
}
render() {
const somevar = 'SomeVar';
return (
<div ref={this.exampleRef} className='class-name' onTouchStart={this.handleEvent}>
{somevar}
</div>
);
}
}
export default Sample;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment