Skip to main content

State in Class Components

File: src/App.tsx

import React, { Component } from 'react'
import Profile from './components/Profile'

class App extends Component {

render() {

const data = {
id: 1,
firstname: "John",
lastname: "Doe",
job: "Developer",
projects: [
{ id: 1, name: "React Frontend Development" },
{ id: 2, name: "UX / UI Design" },
{ id: 1, name: "HR Program" }
]
}

return(
<div>
<Profile person={ data } />
</div>
)
}
}
export default App

File: src/components/Profile.tsx

import React, { Component } from 'react'

class Profile extends Component {

constructor(props) {
super(props)
this.state = {
showProjects: true
}
}

toggleProjects() {
this.setState({ showProjects: !this.state.showProjects })
}

renderProjects() {
if(this.state.showProjects) {
return(
<ul>
{
this.props.person.projects.map( (item, index) => {
return(
<li key={ index.toString() }>{ item.name }</li>
)
})
}
</ul>
)
}
}

render() {

const name = `${ this.props.person.firstname } ${ this.props.person.lastname }`

return(
<div>
<h2>Profile</h2>
<h3>{ name }</h3>
<h4>{ this.props.person.job }</h4>

<button onClick={ () => this.toggleProjects() }>Show Projects</button>
{
this.renderProjects()
}
</div>
)
}
}

export default Profile

Breakdown

There is quite a lot going on here.

  • line 5: first off, if are going to use a state, we need to address the class-variable state (from React.Component)
  • Although the constructor is not necessary (in this case) it's best practice to call it
  • But we need to call the parent constructor first (in JavaScript: super())
  • But now we need to pass the props into the constructor
  • In the state (line 7) we add a variable showProjects
  • line 12 We need a function to toggle the value of the state variable showProjects
  • line 13 utilizing this.setState({ }) to change the value of the state variable
  • line 16 I usually tend to create a separate function which react on state changes (for sake of overview)
  • This functions checks if the state is true/false and acts accordingly
  • On line 42 we add an event listener to the button (anonymous function) which triggers the toggle-function
  • And line 43 to 46 calls the renderProjects-function
  • We can extend the state object indefinitely: this.state({ showProjects: false, showInput: true }) etc