An introduction to jsx in reactjs

An introduction to jsx in reactjs:

JSX stands for JavaScript xml. JSX is used to add XML to JavaScript code or you can think that it allows us to write HTML in React. This is the way that we can build UI in react. Note that we can also write Reactjs applications without JSX. We can do that if we don’t want to setup compilation for our environment.

In react, we can create Components. Components are one UI component that can be reused. For example we can create one component to show the profile of a user and we can reuse that component for different users.

JSX helps us to create the UIs of components easily. Also, with the help of JSX, we can put both markup and logic in a same file. That makes it easy to develop react apps. Compiler like Babel transforms these expressions into JS.

For example, below is a JSX code:

const el = <div>Hello World</div>;

Babel will convert it to :

const el = /*#__PURE__*/React.createElement("div", null, "Hello World");

Using JSX, we don’t have to use React.createElement on each HTML component. We can write them as like pure HTML and the compiler will convert it for us.

Using multiline HTML:

We can put multiline HTML elements in JSX. For example:

const msg = (
    <div>
        <h2>Hello</h2>
        <p>Welcome to our Blog !!</p>
    </div>
);

But we need to make sure that all the lines are wrapped in one tag like div.

We need to close a tag always:

const pic = <Image src={picSource}/>;

How to embed expressions in JSX:

This is one powerful feature of JSX. We can embed expressions and other JSX variables in another JSX variable. For example:

const greet = 'Hello World';
const msg = <h1>Oh !! {greet}</h1>;

We can also use any valid JavaScript expressions inside curly braces in JSX. For example, we can use 4 * 4 or calling a function or accesing any value from JSOn etc.

For putting expressions we are using curly braces. We can’t use quotes here.

Using JSX as expression:

We can use JSX as an expression. For example, we can mix it with conditions like if-else or for/while loop.

For example:

function getMessage(){
    if (morning){
        return <h2>Good Morning !!</h2>;
    }
    return <h2>Good Evening !!</h2>;
}

JSX and attributes:

We can use attributes with JSX elements similar to any other HTML elements. For attributes, JSX uses camelcase notation. It is because few attributes defined in HTML is reserved keyword in JavaScript and it will show one error if we use same attribute.

One example of attribute is className that we can use for class.

For example:

const el = <h1 className='header-bold'>Hello World !!</h1>;

We can also pass one JavaScript expression as the attribute:

const el = <h1 className = {header}>Hello World !!</h1>;

Commenting:

Commenting is allowed in JSX. Commenting begins with /* and ends with */. Comments are wrapped in curly braces. For example:

const el = <div>
{/* Comment in JSX */}
</div>;

You might also like: