Reputation: 752
I've met two approaches to handle events by stateless functional components:
1)
const SomeInputComponent = ({ onTextChange }) => (
<input type='text' onChange={(e) => onTextChange (e.target.value)} />
);
2)
const SomeInputComponent = ({ onTextChange }) => {
const handleChange = (e) => {
onTextChange(e.target.value);
}
return (
<input type='text' onChange={handleChange} />
);
};
Which one is more preferable? What are pros and cons?
Upvotes: 0
Views: 153
Reputation: 2121
My opinion is that it's mostly about readability, reusability, etc. Personally, I try to use option 2, but if it's really simple component and I'll never reuse the handler sometimes i go for option 1.
However, I'm not happy with it and try to stick with second option. Why? Because often I think I will not reuse the handler or I think it will always be a one-liner, but then I end up rewriting it because I'm reusing it or I'm adding more code to it (often simple console.log
). That wastes time.
So I'm for consistency. Always use option 2.
Upvotes: 1