Saturday, June 6, 2020

React JSX

JSX(JavaScript Extension), is a React extension which allows writing JavaScript code that looks like HTML.

All of the React components(class component) have a render function. The render function specifies the HTML output of a React component. 

Look at the code from App.jsx where we are returning div.

Nested Elements

If we want to return more elements, we need to wrap it with one container element. Notice how we are using div as a wrapper for h1, h2
and p elements.

Attributes

JSX uses attributes with the HTML elements same as regular HTML. JSX uses camelcase naming convention for attributes rather than

standard naming convention of HTML such as a class in HTML becomes className in JSX because the class is the reserved keyword

in JavaScript.

class → className

for → htmlFor

onclick → onClick


We can also use our own custom attributes in JSX. For custom attributes, we need to use data- prefix. In the below example, we have
used a custom attribute data-demoAttribute as an attribute for the <p> tag.

JavaScript Expressions

JavaScript expressions can be used inside of JSX. We just need to wrap it with curly brackets {}.

As per the below example, we cannot use if else statements inside JSX, instead we can use conditional (ternary) expressions. In the
following example, variable i equals to 1 so the browser will render true. If we change it to some other value, it will render false.

JSX Comments

JSX allows us to use comments that begin with /* and ends with */ and wrapping them in curly braces {} just like in the case of JSX

expressions.

Styling

React recommends using inline styles. When we want to set inline styles, we need to use camelCase syntax. React will also automatically
append px after the number value on specific elements. The following example shows how to add myStyle inline to h1 elements.

No comments:

Post a Comment