To generate a functional component in VSCode: rcc
Β πΒ Functional Component - good for simple content without logic behind it
Β πΒ Class-Based Component - good for everything else
- Easier code organization
- State - Β Β easier to handle user input
- Lifecycle Events - Β Β easier to do things when app first starts
import React, {Components} from 'react'
class SeasonDisplay extends Components {
render() { // the only requirement of a class function is to have a render method
return (
<div></div>
)
}
}
export default SeasonDisplay
Β πΒ JS object that contains data relevant to a component
Β πΒ Updating state on a component causes the component to rerender
Β πΒ State must be initialized when a component is created
Β πΒ State can only be updated with setState()
using state
class SeasonDisplay extends Component {
constructor(props) { // we are overwriting our parents constructor
super(props) // retaining our parents constructor and just adding to it
this.state = {lat: null } // our state; initializing it to null because we're expecting a number
getLocation(
position => this.setState ({lat: position.latitude}) // changing our state
)
}
render() { // required for a class component
return JSX
}
}
These are methods in our Class-Based Components. React automatically call them at certain points during a components lifecycle. A component's lifecycle goes like this: gets created, shows up in DOM, rerender and in theory gets removed in the DOM altogeher
For instance after render(), componentDidMount() gets called one time after our component gets rendered in our screen. We can put some codes here for our component setup.
Β πΒ Β constructor - good place to do one-time setup
Β πΒ Β render - only for returning JSX
Β πΒ Β componentDidMount - good place to do data loading
Β πΒ Β componentDidUpdate - good place to do more data-loading when state/props change
Β πΒ Β componentWillUnmount - good place to do cleanup
class App extends Component{
state={ lat: null} // this is an easier alternative for initializing state; Babel
componentDidMount(){ // we take care of data loading here
getLocation(
position => this.setState ({lat: position.latitude}) // changing our state
)
}
render() {
return <div>{this.state.lat}</div>
}
}
export default App
Getting a DOM element in React
constructor(props) { // we create the ref in the constructor
super(props);
this.imageRef = React.createRef();
}
render() {
return (
<img ref={this.imageRef} /> // we pass the createf ref to <img />; we get the <img />
) // use this.imageRef
}