Answer the question
In order to leave comments, you need to log in
How to pass states from child component to parent using pure React JS?
Hello. I started learning React JS using the example of implementing a ToDo List application . At the moment, I have implemented the possibility of creating new tasks and faced the problem of deleting them. To describe in detail the essence of the problem, first I will give the code where the tasks themselves are formed.
class CreatorTasks extends Component {
constructor(props) {
super(props);
this.createTask = this.createTask.bind(this);
this.state = {
components: [
]
};
}
createTask() {
this.setState({
components: this.state.components.concat([this.infoAboutTask()])
});
this.clearInputsAfterCreateTask();
}
infoAboutTask() {
return {
id: this.state.components.length + 1,
taskName: document.getElementById('inputTaskName').value,
taskDescription: document.getElementById('exampleFormControlTextarea1').value,
taskImportance: document.getElementById('inputTaskImportance').value,
taskFinishData: document.getElementById('inputFinishDate').value,
};
}
clearInputsAfterCreateTask() {
['inputTaskName', 'exampleFormControlTextarea1', 'inputTaskImportance', 'inputFinishDate'].forEach((item) => document.getElementById(item).value = '');
}
render() {
return (
<div className="d-flex justify-content-between">
// разметка
<div className="newTask">
{
this.state.components.map((item) => (
<Task key={item.id} infoAboutTask={item} />
))
}
</div>
</div>
);
}
}
Answer the question
In order to leave comments, you need to log in
The approach is very bad. You don't have to write like that. To get started, try to study the code of a typical Todo List on github and repeat. I think, after that, an understanding will come why and why this approach is bad.
Give recommendations on this piece === rewrite the entire code from scratch for you.
Key points:
1. Tasks should be stored in the parent component.
2. In Task, in addition to the task, it is necessary to send callbacks for change/deletion.
3. No direct access to the DOM. To solve your problem, you can even do without ref. Operate with the state.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question