JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
Next
react
junior
jsx

What is JSX and why does React use it?

jsx
syntax
fundamentals
babel
Quick Answer

JSX is a syntax extension that allows writing HTML-like code in JavaScript. React uses it because it provides a familiar, readable way to describe UI structure while leveraging JavaScript's full power for logic and expressions.

Detailed Explanation

What is JSX:

  • JavaScript XML - a syntax extension for JavaScript
  • Looks like HTML but gets compiled to JavaScript function calls
  • Not required for React but recommended for readability

How JSX Works:

  • Babel transforms JSX into React.createElement() calls
  • Each JSX element becomes a plain JavaScript object describing the UI
  • This is called a 'React element'

Key Differences from HTML:

  • Use className instead of class
  • Use htmlFor instead of for
  • Style accepts objects, not strings
  • All tags must be closed (including self-closing)
  • camelCase for event handlers (onClick, onChange)

Benefits:

  • Visual representation of UI structure
  • Compile-time error checking
  • Full JavaScript expressions within {}

Code Examples

JSX basics and transformation
// JSX syntax
const element = (
  <div className="greeting">
    <h1>Hello, World!</h1>
    <p>Welcome to React</p>
  </div>
);

// Gets compiled to:
const element = React.createElement(
  'div',
  { className: 'greeting' },
  React.createElement('h1', null, 'Hello, World!'),
  React.createElement('p', null, 'Welcome to React')
);

Resources

React Docs - Writing Markup with JSX

docs

React Docs - JavaScript in JSX with Curly Braces

docs

Related Questions

What is the difference between functional and class components in React?

junior
components
Next
What is the difference between functional and class components in React?