React - changing class depending on state

Hey everyone,

I’m at the very beginning of the react journey and I’m trying to update a class depending on the state. However, it keeps being stuck on false. Does anyone know why?

import React, { Component } from 'react';

class List extends Component {
  constructor(props) {
    super(props);
    this.state = {
      task: { name: props.name,
          due_date: props.due,
          completed: false
        }
    }
    this.markAsDone = this.markAsDone.bind(this)
  }
  markAsDone(){
    this.setState(state => ({completed: true}))
  }
  render() {
    return (
      <div>
        <h1>My tasks</h1>
        <ul>
          <li className={this.state.task.completed ? "done" : "open"}>{this.state.task.name}</li>
          <li>Due: {this.state.task.due_date}</li>
          <button onClick={this.markAsDone}>Done</button>
        </ul>
      </div>
    );
  }
}

export default List;
1 Like

Hey,
You might want to check this out

1 Like

Just to point out that the component begins with this state

{ task: {
  due_date: ...,
  completed: false
  }
}

if you observe the your set state function however, the structure of this.state becomes

{
  completed: true
}
1 Like

Based on a StackOverflow thread here, it appears that React’s setState is not primarily built for nested properties e.g .you have another property within a property in the state object:

this.state = {
  task: { completed: true  }
}

In your code, you are not changing the task object but instead modifying the state to not have task and it will only have completed property. For instance:

this.state = {
  task: { completed: true  }
}

…will then become:

this.state = {
   completed: true,
}

There are workarounds for this issue and you can find them in the SO thread I linked and the article posted by @Annestezia.

1 Like