Last active
June 12, 2020 22:52
-
-
Save jmhungdev/11c7072416da37af371b410db2c6e799 to your computer and use it in GitHub Desktop.
A generic template for a React class component
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
import React from 'react'; | |
//alternatively you can write: import { Component } from 'react' | |
//and define your class this way: class App extends Component | |
class App extends React.Component { | |
//initiate your class component with a constructor | |
constructor(props) { | |
//inherit the props from React.Component class by using super() | |
super(props) | |
// define state storage | |
this.state = { | |
//here we have a state named 'tracking' that is initialized with a value of empty array | |
tracking = [], | |
} | |
//bind your method to the instance of the App class inside constructor | |
this.run = this.run.bind(this); | |
} | |
//define your own method, in this case it's named 'run' | |
run() { | |
console.log('logging run method'); | |
} | |
//render is a native method that doesn't need binding | |
render() { | |
//make sure your have return inside the render method | |
return ( | |
//always wrap your jsx with a parent tag such as <div> | |
//or you can wrap it with React.Fragment alternatively | |
<div> | |
<h1>HELLO WORLD!</h1> | |
<!-- onClick attribute listens to mouse click event and dispatches this.run when triggered | |
make sure you pass in function definition as a value of attribute, equivalently you can pass ()=>{this.run()} --> | |
<button onClick={this.run}>Click to Run</button> | |
</div> | |
) | |
} | |
} |
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
// In this file we'll demonstrate fetching data pattern withint a React component |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment