Last active
June 24, 2020 03:55
-
-
Save jooeycheng/d9beef2b94385878ac748a7cfe5c5550 to your computer and use it in GitHub Desktop.
Example React Component (cheatsheet)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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