A Live Developer Journal

React Jsx

Create elements with blended HTML and JS

JSX allows us to create elements using a blend of HTML and JavaScript syntax, which is easier to read and write than pure JavaScript alone.

For example, if we want to create a blue button with the text "Click Me!", we can write it in JSX like this:


const button = (
  
);

Note: The parenthesies surrounding the JSX code are optional, but help prevent semi-colons being inserted in the wrong place by editors/browsers as a result of the multi-line HTML

This is similar enough to how we create elements in HTML that it's easy to remember. Without JSX, we would have to remember the syntax for using React's createElement method to acheive the same thing, which looks like this:


React.createElement(
  button,
  { className: 'clickme', color: 'blue' },
  'Click Me!'
)

Note: Babel compiles JSX into React.createElement calls

Note on separating concerns

Front-end developers are typically encouraged to seperate content (HTML), presentation (CSS) and behaviour (JS) files from each other (Avery, 2016). The main benefit of doing this is that it's easier to find and change things when you don't have to wade through unrelated markup or code.

Components are a way to seperate concerns by grouping chunks of HTML, CSS and JS into self-contained user-interface elements . A good thing about this approach is that if you want to change something about a specific element like a button or a form etc, everything you need to do so is in one place (Avery, 2016). This an example of the Single Responsibility Principle (SOLID principles) where 'things that change together stay together' (Martin, 2014, Janssen, 2020).

Embed dynamic content into elements in a single step

Creating an element in vanilla JavaScript involves creating individual elements, setting their attributes, properties and text content in multiple steps steps, before appending them all together in another step. Whereas JSX lets us do the same thing in a single step.

If you want to create HTML elements in JSX that have custom content, properties and attributes without having to hard-code them, then JSX let's you use curly braces to replace these values with JavaScript variables or function results (React, 2020). Like this:


const pet = (
  <div>
      <h2></h2>
      <p></p>
      <p>Color: </p>
  </div>
);

JSX Prevents injection attacks

Any user input that is passed into a React component that is created using JSX syntax, is escaped by converting it into a string (including HTML tags, quotes and any kind of programming language syntax). Escaping user input means that a malicious user won't be able to pass in code that could change how the site works (code injection attacks), because it'll be converted into a format that the browser won't recognise as executable code (React 2020, Stack Overflow, 2020).