Repository navigation
4 class components
In the previous workshop we used Functional components, basic building blocks of React. React has two main types of components: functional and class.
Lets look at the different forms:
Functional:
const Name = props => {
return <p>{props.firstName}</p>
}Class:
class Name extends React.Component {
render() {
return <p>{this.props.firstName}</p>
}
}The biggest difference is that Class components have "state" and "lifecycle hooks".
State is local storage, held withing a component.
Lifecycle hooks are events or moments in the creation and usage of components, as they are loaded by other components etc.
So, how to choose? Try to use functional components for presentational aspects of your project, and class components where some logic is required, or you need to use state.
Breaking news, functional components can now use state and hooks too... stay tuned for workshop update.
Let's build a toy app using class components, and use local state.
If your app from previous workshops is still running, end it in the terminal with Control-C
Get back into your sandbox directory, make a new toy app and start it. Also, open your app code in your IDE.
cd ~/sandbox
npx create-react-app react-state
cd react-state
yarn startCreate a new Name.js file in src and make the new Name class component.
- We begin with importing React, so we get access to the fun React library.
- Then we define the class, and extend the features of the
React Componentclass. - Inside the Name class, we start by initialising the local state object, giving whatever default parameters we want. In this example, the state object is being set to having a parameter called "name" with a starting value "hello".
-
ComponentDidMountis a lifecycle hook which will be run when this Name component is mounted (eg loaded by another component). In this example, the state is updated to combine the word "hi" with thefirstNameprop that is passed into this component. Note that we don't set the state object directly, but use thesetStatefunction. - The
renderfunction is drawn when the component is mounted, and it writes the state name value in a paragraph tag. - Then we export the class so that it can be imported elsewhere.
import React from 'react'
class Name extends React.Component {
state = {
name: "hello"
}
componentDidMount() {
this.setState({ name: "hi " + this.props.firstName })
}
render() {
return <p>{this.state.name}</p>
}
}
export default NameThis is done the same way we do with functional components, so open App.js and import the Name component. Then add it to the JSX that is rendered (rip out all the other stuff that was there).
import React from 'react'
import Name from './Name'
import './App.css'
function App() {
return (
<div className="App">
<header className="App-header">
<Name firstName="baby" />
<Name firstName="shark" />
</header>
</div>
)
}
export default App