Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do semicolons throw error in react JSX?

Tags:

reactjs

jsx

Below is part of my render method in JSX - why does the semicolon after the }) throw an error? It's perfectly fine in normal JavaScript

<ul>
    {
        libraries.map(function (item) {
            return <li>{item.name.toLowerCase()}</li>;
        });
    }
</ul>
like image 902
mangocaptain Avatar asked Aug 10 '16 23:08

mangocaptain


People also ask

Does semicolon matter in React?

It doesn't matter.

Why does React use JSX instead of putting markup and logic in separate files?

JSX may remind you of a template language, but it comes with the full power of JavaScript. JSX produces React “elements”. Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both.

Is JSX compiled or interpreted?

JavaScript is an interpreted language, not a compiled language. A program such as C++ or Java needs to be compiled before it is run. The source code is passed through a program called a compiler, which translates it into bytecode that the machine understands and can execute.

Is it mandatory to use JSX in React?

JSX is not a requirement for using React. Using React without JSX is especially convenient when you don't want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.


1 Answers

It's because JSX {} expressions are limited to a single expression.

<div>{2 + 2; 3 + 3}</div>

..will throw an error.

However you can solve this by having two {} expressions

<div>{2 + 2}{3 + 3}</div>

There's no need for semi-colons if there will only be a single expression.

If you want to get all hacky about it, you can use the lesser known comma operator in expressions to do some local work, before returning the last expression separated by commas:

let x
...
<div>{x = 20, x}</div>

Which will display <div>20</div>

You might not need semi-colons anywhere.

like image 53
azium Avatar answered Oct 06 '22 23:10

azium