Is it possible to remove the extra arrow function here?
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
Hi!
The tutorial has an example like this:
class Square extends React.Component {
render() {
return (
<button
className="square"
onClick={() => this.props.onClick()}
>
{this.props.value}
</button>
);
}
}
This component used in the Board component like this:
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={() => this.handleClick(i)}
/>
);
}
We have closed the context in a function that we pass to onClick in the Board component.
But why don't we just pass this.props.onClick to onClick in the Square component? Why are we using closures here if we already have the right context inside?
I wrote like this: (link to codepen)
class Square extends React.Component {
render() {
return (
<button
className="square"
onClick={this.props.onClick}
>
{this.props.value}
</button>
);
}
}
This works successfully
It is clear that the variant from the tutorial will also work. But further it says:
When we modified the Square to be a function component, we also changed onClick={() => this.props.onClick()} to a shorter onClick={props.onClick} (note the lack of parentheses on both sides).
So my variation only works in a functional component? But above it also worked in class components. I think this might confuse some people.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the linked tutorial sections on lifting state up and function components, then compare the two onClick examples and the accompanying explanation. Check whether the class-component example needs clarification about passing a callback versus invoking it. Done means the tutorial clearly explains why both forms work and when the shorter form is appropriate.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100