React by Ben

JSX

JSX (JavaScript XML, ReactJS) is a syntax extension for JavaScript that allows you to write UI code that looks like HTML, directly inside your JavaScript files.

It’s a core part of how React components are written. JSX is not required to use React, but it makes the code more readable and expressive.

Why JSX Matters

  • It brings HTML-like syntax to JavaScript.
  • It provides a clear visual structure for UI components.
  • It makes combining markup with logic simple and intuitive.

Example:

const button = <button>Click Me</button>;

React transforms this into standard JavaScript using React.createElement() behind the scenes.

🔍 Want to Learn More?

Check out the child Snipp “Understanding JSX” for syntax rules, common mistakes, and practical examples.

jsx
react
syntax
fundamentals
intro
...see more

JSX supports expression in pure JavaScript syntax. The expression has to be enclosed inside the curly braces, { }. The expression can contain all variables available in the context where the JSX is defined. Let us create simple JSX with expression.

Example

<script type="text/babel">
   var currentTime = new Date().toTimeString();
   ReactDOM.render(
      <div><p>The current time is {currentTime}</p></div>, 
      document.getElementById('app') );
</script>

Output
Here, cTime is used in the JSX using expression. The output of the above code is as follows,

15:57:48 GMT-0700 (Pacific Daylight Time)

One of the positive side effects of using an expression in JSX is that it prevents Injection attacks as it converts any string into an HTML-safe string.

...see more

JSX supports user-defined JavaScript functions. Function usage is similar to expression. Let us create a simple function and use it inside JSX.

Example

<script type="text/babel">
   var currentTime = new Date().toTimeString();
   ReactDOM.render(
      <div><p>The current time is {currentTime}</p></div>, 
      document.getElementById('app') 
   );
</script>

Output
Here, getCurrentTime() is used to get the current time, and the output is similar as specified below −

16:37:32 GMT-0700 (Pacific Daylight Time)
...see more

JSX may look like HTML, but it’s actually JavaScript. When used correctly, it brings power and clarity to React development.

Why Use JSX?

  • It’s familiar to anyone who has written HTML.
  • You can mix logic and layout using {} for JavaScript expressions.
  • JSX is compiled into fast and efficient React code.

Key JSX Rules

  • Use className instead of class.
  • Self-closing elements like <img />.
  • Wrap multiple elements in one parent: <div> or <>.

Example:

function Greeting() {
  return <h1>Hello, world!</h1>;
}

Common Mistakes

  • Forgetting to close tags.
  • Using class instead of className.
  • Returning multiple sibling elements without a wrapper.

Comments