Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Facebook's React JSX transformer work?

How is it even possible that React allows you to write JSX (XML) within javascript without it throwing any errors? I have been trying to wrap my head around it, and I am not quite sure how the underlying code accomplishes this.

like image 585
SMLMRKHLMS Avatar asked May 14 '15 19:05

SMLMRKHLMS


People also ask

How does React JSX work?

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications.

What tool does React use to compile JSX?

Browsers don't understand JSX out of the box, so most React users rely on a compiler like Babel or TypeScript to transform JSX code into regular JavaScript.

Can Web browsers read JSX directly?

Browsers can't read JSX because there is no inherent implementation for the browser engines to read and understand them. JSX is not intended to be implemented by the engines or browsers, it is intended to be used by various transpilers to transform these JSX into valid JavaScript code.


1 Answers

Simple, it looks for <script type="text/jsx"> tags, parses them, generates the corresponding javascript code, and eval's it.

This is why the jsx inline transformer should be used only when developing, as having to parse the jsx code decreases the performance of your web page. When deploying, you should convert all jsx code into js one before deploy.

like image 77
Cristik Avatar answered Sep 22 '22 22:09

Cristik