TIL - Classes & React Components
January 21, 2020
What follows is notes from a class. Incomplete thoughts & code that probably will only make sense to me. Given enough time, even that may be a stretch! Reference at your own risk 😂
- An object is an instance of a class
- Classes can be extended
- For React to work in Codepen, add react, react-dom, and Babel as the preprocessor in Codepen settings
Slides
Basic Stateless Component
function FirstComponent() { |
Basic Stateless Component With Props
function FirstComponent(props) { |
React Fragments no longer require the Fragment
keyword
Empty angle brackets do the same job. This is because the render method can only take one element to render, so if you need to render multiple components, they need to be wrapped in a single fragment.
ReactDOM.render( |
React can only return
and render
a single element.
React Props Can Be Hard Coded Or Evaluated
function FirstComponent(props) { |
Output:
Hiya Nia. You are 87.
Hiya Shelly. You are 87.
Hiya Barry. You are 87.
React Context API
This seems pretty useful—check it out!
Two Adjacent Counter Components
When components need state they are set up as a class instead of a function.
class Counter extends React.Component { |
React Component Lifecycle Methods
There are some methods in React.Component
by default: construction –> pre-render –> render –> post-render (aka birth, life, and death methods). Read about them in the React docs.
When a React component is extended, your own methods will overwrite the defaults. This is called method overload. Example:
class Timer extends React.Component { |
Key Takeaways:
componentDidMount()
is the go-to method for doing things with your component knowing it’s loaded & ready on the pagecomponentWillUnmount()
is the go-to method for scrapping anything you’ve set up in the component which will take memory. React scraps the component when it’s no longer needed but it doesn’t automatically scrap things the component did so this must be done manually withcomponentWillUnmount
. In the above example the timer would just keep running forever otherwise.