Background
I am trying to get familiar with React by creating a To Do App, using the React documentation.
Side note, I am using classes
as components rather than functions
.
Problem
When a value (this.props.completed
) is changed, the className
should also change, depending on the completed
status. But in my current situation – it’s not updating the className
and I can’t figure out why.
Logic:
'completed == true' then set the className = 'taskCompleted'
'completed == false' then set the className = 'taskNotCompleted'
Below is the app, both <div />
elements has class names set to taskNotCompleted
, whilst the completed
status is set to false
, as shown in red on the left hand side of the image:
Next…
Clicking the done
button for the 1st task, the completed
status is changed as shown in the image below in blue border. But the className
has not changed (red border).
this is my Task Class
:
class Task extends React.Component {
constructor(props) {
super(props);
}
render() {
const isCompleted = this.props.completed;
return (
<div className={`task ${isCompleted == true ? 'taskCompleted' : 'taskNotCompleted'}`}>
<h2>{this.props.title}</h2>
<p>{this.props.description}</p>
<button onClick={this.props.handleChange}>Done</button>
<p>{this.props.completed}</p>
<p></p>
</div>
)
}
}
I have found this resource: https://stackoverflow.com/a/35225464/12485722 I noticed within the answer, my className
is very similar to the answer. Still no ideas why it’s going wrong.
Full Code
class App extends React.Component {
render() {
return (
<Tasks />
)
}
}
class Tasks extends React.Component {
constructor(props) {
super(props);
const tasksList = [{
id: 1,
title: "Title 1",
description: "description 1",
completed: false
}, {
id: 2,
title: "Title 2",
description: "description 2",
completed: false
}]
this.state = {
tasks: tasksList
}
this.alterStatus = this.alterStatus.bind(this);
}
alterStatus(id) {
const tasks = Object.assign([], this.state.tasks);
tasks.forEach(element => {
if (element.id == id) {
element.completed = true;
}
});
this.setState({ tasks: tasks });
}
render() {
return (
<div>
{this.state.tasks.map((task) =>
<Task
key={task.id}
title={task.title}
description={task.description}
completed={task.completed.toString()}
handleChange={() => this.alterStatus(task.id)} />
)}
</div>
)
}
}
class Task extends React.Component {
constructor(props) {
super(props);
}
render() {
const isCompleted = this.props.completed;
return (
<div className={`task ${isCompleted == true ? 'taskCompleted' : 'taskNotCompleted'}`}>
<h2>{this.props.title}</h2>
<p>{this.props.description}</p>
<button onClick={this.props.handleChange}>Done</button>
<p>{this.props.completed}</p>
<p></p>
</div>
)
}
}
export default App;