JAVASCRIPT XML

JSX – JavaScript XML

JSX stands for JavaScript Extension or JavaScript XML.

JSX is the HTML-like syntax that is used by React components to render in the browser.

“React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.” — reactjs.org

By using JSX, we can write HTML-like structures in the same file as we write JavaScript code, then Babel will transform these expressions into actual JavaScript code. Unlike in the past, instead of putting JavaScript into HTML, JSX allows us to put HTML into JavaScript.

By using JSX, we can write the following JSX code:

Bable will transform it into this:


So, we can think of JSX as a shorthand for calling 
React.createElement(). JSX is easier to read and write over large pyramids of JavaScript function calls or object literals. Additionally, the React team clearly believes JSX is better suited for defining UI’s than a traditional templating solution.

  1. JavaScript expressions can be used inside JSX. We just need to wrap it with curly brackets {}.
  2. HTML tags always use lowercase tag names, while React components start with Uppercase.
  3. In the case of styling, react recommends using inline styles. When we want to set inline styles, we need to use camelCase syntax.
  4. We cannot use if-else statements inside JSX, instead, we can use conditional (ternary) expressions.

JAVASCRIPT XML and JS

JSX is easy to understand, but as a newcomer to JSX, there are a few things you need to keep in mind.

  • Variables

Whenever you want to render a variable/expression in JSX, you need to wrap them with curly braces {}. You can include any JS expressions within curly braces.

  • Rendering nothing

Return null if we want to React to not render content to the UI. When we return undefined[](empty array), boolean values also, React wouldn’t render any content, but null is good to use as the code can be easily readable by fellow developers.

  • Conditional rendering

     There are three ways to conditionally render content in React.

  • If/Else

This is the general syntax we use in most programming languages.

  • Ternary Operator

We can also use the traditional ternary operators in JSX to render conditionally. 

  • Logical Operator

We can also use the logical AND operator && also to render conditionally. When this is used, only if the first condition is true the content will be rendered.

 

Leave a Reply