React jsx hello world

JSX is a JavaScript syntax extension that looks similar to XML. It is used by React code and it is optional to use JSX. Everything which is written in JSX can be written in javascript also.

JSX syntax

Here is how the JSF syntax look like:

<script type="text/babel">
// react jsx code
</script>

Note that here type value is text/babel which prevent browser to interpret it as Javascript. It also tells React and babel compiler javascript code to process it as jsx.

JSX hello world

Here is basic jsx example and how it renders. Note that we have used inline JSX for better readability. It is better to keep jsx code in separate file.

<script src="https://fb.me/react-0.14.7.js"></script>
<script src="https://fb.me/react-dom-0.14.7.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>

<div id="hello"></div>
<script type="text/babel">
ReactDOM.render(
  <h1>Hello world</h1>,
  document.getElementById('hello')
);
</script>
refresh

Few points to note

  1. If you inspect hello world element in Chrome, here is how the dom element looks like. Note the presence of data-reactid property of h1. React uses it internally to manage this element.
    react-jsx-hello-world-inspect-dom
  2. Babel javascript compiler is needed for parsing JSX code in the page.
  3. Earlier react was using JSTransform for transforming jsx code. JSTransform is now deprecated.
  4. It is better to transform JSX offline to avoid browser do extra work. Offline it is done only once.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments