I'm new to React and ES6 syntax, and something I found interesting was that if I write:
return <input onChange={event => console.log(event.target.value);} />;
This will not work. I get a "Cannot find module" error.
But if I remove the semicolon in the arrow function:
return <input onChange={event => console.log(event.target.value)} />;
It works just fine. And if I kept the semicolon but added braces, as so:
return <input onChange={event => { console.log(event.target.value); }} />;
This works too. What is the reason for the first example above not working?
I'm new to React and ES6 syntax, and something I found interesting was that if I write:
return <input onChange={event => console.log(event.target.value);} />;
This will not work. I get a "Cannot find module" error.
But if I remove the semicolon in the arrow function:
return <input onChange={event => console.log(event.target.value)} />;
It works just fine. And if I kept the semicolon but added braces, as so:
return <input onChange={event => { console.log(event.target.value); }} />;
This works too. What is the reason for the first example above not working?
Share Improve this question asked May 24, 2018 at 4:36 rb612rb612 5,6033 gold badges35 silver badges80 bronze badges1 Answer
Reset to default 7To properly understand why this is the case, let's make sure we know the difference between an expression, and a block.
At the most basic level, an expression is a bit of code that represents a value of some sort. So 123
, a + b + c
, calculateSomething()
, these are all expressions. Expressions don't include semicolons in them.
A block in JS is a list of statements. These statements are surrounded by curly braces { }
, and separated by semicolons.
Quite often, statements consist of an expression followed by a semicolon. So,
a = b + c;
is a statement. There are other kinds of statements: let
, var
, for
, while
, return
, etc.
Now, back to the arrow function. An arrow function can e in two forms:
(some, args) => <an expression>
(some, args) => { <a statement>; <a statement>; ... }
Note the first form takes an expression, a single one. There should only be semicolons if you're using a block, like in the second form.
JSX works like this:
<input onChange={ <an expression> } />
You put the name of the prop you want, an equal sign, then a single expression in braces. Remember, single expressions don't have semicolons.
An arrow function is an expression. So, if you were to put a semicolon here...
<input onChange={ () => 'hello' ; } />
JS will see the expression, then see the semicolon after it and crash, because it's not supposed to be there.