Earlier in "Hello World!!" Example, we used ReactDOM.render() method to hook our React code into actual DOM. This process remains same in any application you are going to develop using React.

React Elements

Before jump starting into JSX, lets discuss about React Elements. React elements are the building blocks of React apps. They are plain JavaScript objects which represent DOM nodes. Since they are JavaScript objects, React can easily create and destroy them. React internally analyzes these objects and can check what has changed from the previous object and then only updates the actual DOM where changes occurred. This feature has significant performance improvement.

we use createElement method of React library to create elements that represent DOM. This method takes three parameters. The first is the tag name used to represent element example div, span, h1 etc... They can also contain user created elements. Second is an object that represents attributes required for style, class, id, events, data etc... also called as props and third is the children inside the tag, it can be a simple text or another element.

Let's see an example

var ele = React.createElement('h1', null, "Hello World !!");
ReactDOM.render(ele, container1);

This is the simplest form of using a createElement method. We are creating header tag with no attributes and its children is a plain text "Hello World". So the output of above code is

<h1>Hello World !!</h1>

React Elements are nothing but plain JavaScript Objects, so the above created element looks like below object

var ele= {
    key: null,
    props: {
        children: "Hello World!"
    },
    ref: null,
    type: "h1"
};

These are the objects used for determining what was changed and then update only what was necessary by React. This concept is called Virtual DOM.

  • key - the key property is used to uniquely identify specific React elements within an array of the same element types. It's not mandatory value, but if provided will be used by React for better performance.
  • props - It’s a mapping of all the props and values passed down to child components.
  • ref - This property is used to access the underlying DOM element associated with a rendered version of this React element.
  • type - the type property will either be a valid HTML element or a reference to a user created components.

Let's create a element with styles and event listener

var bgColor = 'black';
function clicked() {
    if(bgColor === 'black') {
        bgColor = 'yellow';
    }else {
        bgColor = 'black';
    }
    alert(bgColor);
    ReactDOM.render(ele2, container2);
}
var ele2 = React.createElement('h1', {style: { color:'green', 
cursor:'pointer', backgroundColor: bgColor }, onClick:clicked
}, "Hello World !!");

ReactDOM.render(ele2, container2);

In the above example, even if we changed the background color of the element it's not getting reflected in the UI. The reason is React elements are immutable, once they are created they cannot be changed, you need to create a new element again and replace it with.

Creating React elements like the above is a hectic task and even for accomplishing a small task you end up writing more lines of code. This is where JSX comes into the picture. In simple words JSX lets you write React elements in a more efficient way. At the end of the day, all the JSX code is compiled down to React elements.

Summary

  • React elements are JavaScript objects and they represent DOM nodes.
  • React elements are building blocks of React application. React Components will compile down to React elements
  • React elements are light weight and immutable, once created cannot be changed.
  • Instead of writing React elements directly, we use JSX to create Components. JSX acts as abstraction layer and will always transpiled to React.createElement via Babel.

JSX Introduction

JSX stands for JavaScript XML syntax transform. JSX is an abstraction layer provided by React for React.createElement. JSX helps you to write React elements in a more convenient and maintainable way. Just like XML, JSX tags have names, attributes and children. JSX tags will almost look like HTML tags, but they are not. Since JSX is JavaScript, identifiers such as "class" and "for" are discouraged as XML attribute names. Instead, React DOM components expect DOM property names like "className" and "htmlFor", respectively. While writing JSX all the HTML attributes and style properties are used in camel-case words. All the HTML tags will be in lower case where as Component tags will start with capital letter. JavaScript expressions can be evaluated inside JSX using single curly braces.

JSX is not supported by browsers by default. We have to compile it to JS and this is done by babel transpiler.

Let's write some examples.

  • JSX Introduction Example
<h1>JSX Introduction</h1>

This is a very basic example of JSX. Here I have a h1 tag with no attributes and a string as it's children. This is what exactly you see when it transpiled into React.createElement

  • JSX with class, style, id and event listener
<div id="attrId" className="jsx-class" 
    onClick={divClicked}> 
    JSX with Attributes 
</div>
  • JSX with multiple children
<div id="container">
<header id="header"></header>
<App id="app">
<div>App Area</div>
</App>
<footer id="footer"></footer>
</div>
  • JSX Expression evaluation
function Test() {
    let a = 10
    return (
        <div>
            <p>{a}</p>
            <p>{a + 10}></p>
            <p>{new Date().toString()}</p>
        </div>
    )      
}

Summary

  • JSX is a JavaScript with XML. It lets you write React components in an effective way.
  • class and for keywords in HTML are replaced with className and htmlFor respectively because they are reserved keywords in JavaScript.
  • JSX is not supported by the browser, we use babel transpiler to compile JSX to React elements.
  • Expressions are evaluated using single curly braces.
  • All the html attributes, style properties will be CamelCase.
  • Single and multi line comments are supported using {// single line comment} and {/* multi line comment */}
  • All the html tags will be lower case and React Components will be upper case.

results matching ""

    No results matching ""