I have followed React JS Crash Course - 2019 on youtube and I was not able to find the answer to the following question.
Why the method context in parent component is not overwritten by the child bind call.
The codebase can be found here https://github.com/bradtraversy/react_crash_todo
But to simplify the question here is a small code snippet.
Parent
class App extends Component {
state = {
todos: []
}
// Toggle Complete
markComplete = (id) => {
this.setState({ todos: this.state.todos.map(todo => {
if(todo.id === id) {
todo.completed = !todo.completed
}
return todo;
}) });
}
render() {
return (
<TodoItem markComplete={this.markComplete} />
);
}
}
Child
export class TodoItem extends Component {
render() {
const { id, title } = this.props.todo;
return (
<input type="checkbox" onChange={this.props.markComplete.bind(this, id)} /> {' '}
)
}
}
From my understanding of bind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind I would expect that when the mark markComplete is called that the "this" would be the child context but it stays the parent.
markComplete = (id) => {
this.setState({ todos: this.state.todos.map(todo => {
^^^^ why it is not child
if(todo.id === id) {
todo.completed = !todo.completed
}
return todo;
}) });
}
I do understand the public class fields syntax.
Is react doing some magic? https://github.com/facebook/react/blob/64e1921aab4f7ad7e2f345f392033ffe724e52e9/packages/events/EventPluginHub.js#L148
From answer @Li357 https://stackoverflow.com/a/51759791/4322180