Shown below is a snippet of the declaration of a function in my react component:
increment() {
this.setState(state => ({
count: state.count + 1
}));
}
Notice that there is parenthesis right after the arrow. I do not understand why this code wouldn't work without the parenthesis, since it wasn't required in another similar case:
toggleVisibility() {
this.setState(state => {
if (state.visibility === true) {
return { visibility: false };
} else {
return { visibility: true };
}
});
}
When do I use the parenthesis?
I'm a new self-learn coder, please be kind on me! Many thanks.
It's not really a react thing, it's a javascript syntax. Using parenthesis is a shortcut for returning an object.
For example,
const items = [1, 2, 3, 4, 5]
const withParenthesis = items.map((item) => ({item}));
// is the same with
const withoutParenthesis = items.map((item) => {
return {item};
})
Keep in mind that you need to manually
return when not using ({})