Understanding The Mystery Of JSX And It's Relevance To React

React is a JavaScript library for the building of User Interface (UI). With React, developers can build reusable pieces of code in separate files known as Components. These components are independent and are meant to perform a specific task in your web application like rendering out some HTML. The  concept of separation and reusing of these components makes React modular.

To better understand components, think HTML tags or elements. In HTML, you structure the contents inside of tags like using the <h1> tag for headings and placing links in <a> tags.

With React, you can  "create" your own elements and supply these elements with contents. The creating of elements is done primarily with the React.createElement() method like this.

However, elements creation can be made with a simplified syntax. What is this syntax? Steps in JSX.

JSX is a JavaScript extension that can be used for writing of HTML. JSX can be used to create React elements. While it has the full features of JavaScript, one of the mysteries of JSX lies in the fact that it is not understood by web browsers, hence must be compiled into JavaScript using babel before it is rendered in the DOM.

We can reproduce the sample code above in JSX like this:

Some Key Features of JSX

1. JSX elements can be used in expressions. Since JSX elements are an extension for JavaScript, its elements can be return as a function, assigned to a variable or an object like this:

2. JavaScript expressions can be placed inside JSX. JavaScript expressions are placed in JSX inside a curly brace like this:

3. Attributes in JSX.  Attributes are written in quotes just like in HTML. 

All self closing tags (empty tags) must be closed in XML format like this />..

Note that the attribute  "class" as used in HTML is not allowed in JSX. Use "className" instead. This is because "class" is a reserved word in javaScript.

4. Support for one parent element. JSX allow the return of one parent element. To wrap children around JSX elements, use the div tag to contain the children elements.

For cleaner codes and readability, your JSX can span multi-line by enclosing it in parenthesis.

Putting It All Together - Displaying  JSX Elements in React

How do JSX elements get displayed on the browser? Steps in the render() method. The render() method is usually attached to the ReactDOM library.

Here is a quick example.
JSX not only allow you to write HTMl inside of a javaScript file. It also creates React element and has the full features of javaScript.


Popular Posts