Writing Markup with JSX: A Comprehensive Guide
This comprehensive guide walks you through JSX, the markup language that brings React components to life. We'll start by laying down the basics of how JSX extends JavaScript with HTML-like syntax, and why most React developers love working with it. You'll learn the practical rules for writing valid JSX—like why each file needs a single root element and how to properly close your tags. The guide then dives into the nitty-gritty of converting HTML to JSX, with tips for dealing with special attributes and reserved words. We'll also show you how JSX handles JavaScript objects and expressions, with detailed examples of passing props and styling components. Along the way, you'll discover how to work with textarea elements, manage form inputs, and handle events in React. By the end, you'll be confident in your JSX skills, with the ability to write efficient, maintainable code that follows React's best practices.
JSX extends JavaScript with HTML-like syntax, integrating rendering logic and markup within components while maintaining separation between unrelated elements. Most React developers prefer this concise approach, which combines JavaScript logic and content within the same file, as demonstrated in React's architecture.
The browser console provides helpful error messages when parsing invalid JSX, guiding developers towards correct markup structures. JSX enforces strict rules: each file must return a single root element, which may be wrapped in a
or <React.Fragment> for multiple elements. All tags must be properly closed, with self-closing tags like requiring an / after the opening angle bracket.
The syntax converts most HTML attributes to camelCase for property names, though several reserved words remain unchanged. For example, stroke-width becomes strokeWidth and class becomes className. JSX mirrors HTML but handles special attributes differently, writing aria- and data- attributes with dashes to maintain correct syntax.
Developers can convert existing HTML and SVG code to JSX using a converter tool or manual translation. The process requires attention to the JSX-specific rules, particularly regarding the proper use of curly braces for JavaScript integration. The parser provides guidance on correcting invalid markup through console messages, helping developers transition smoothly to the JSX syntax.
To convert HTML to JSX, each file must return a single root element, with multiple elements wrapped in a parent tag like
or the <React.Fragment> component to avoid leaving behind browser-specific HTML traces. All tags must be explicitly closed, including self-closing tags like , which become in JSX syntax. The parser provides guidance through the browser console, helping developers correct invalid markup.
The syntax conversion requires translating camelCase for most properties, while reserved words like class become className. While the recent updates now apply camelCase most of the time, understanding the full rule set ensures correct transformations. For example, stroke-width becomes strokeWidth, and class becomes className, following the updated JSX naming conventions.
Developers can use a JSX converter tool for translating existing HTML and SVG code, though manual translation is also possible. The process benefits from attention to JSX's specific rules, particularly the proper use of curly braces for JavaScript integration. The browser console provides helpful error messages when parsing invalid JSX, guiding developers towards correct syntax and structure.
Most JSX attributes convert directly to JavaScript objects with camelCase property names, except for reserved words like class which becomes className. Some attributes remain unchanged, such as aria-* and data-* which require dashes in the attribute name.
The JSX parser provides guidance through the browser console, helping developers correct invalid markup. For example, React handles attributes like style using camelCase, so stroke-width becomes strokeWidth, and class becomes className.
Objects are denoted with curly braces, like { name: "Hedy Lamarr", inventions: 5 }. In JSX, passing a JavaScript object requires wrapping it in another pair of curly braces: person={{ name: "Hedy Lamarr", inventions: 5 }}. JSX supports inline styles within objects: style={{ backgroundColor: 'black', color: 'pink' }}.
The syntax supports multiple expressions combined into one object: const person = { name: 'Gregorio Y. Zara', theme: { backgroundColor: 'black', color: 'pink' } };. This allows referencing values directly in JSX: <div style={person.theme}> <h1>{person.name}'s Todos</h1>
Curly braces enable JavaScript logic within JSX through two primary methods:
Directly inside JSX tags: <h1>{name}'s To Do List</h1>
As attributes immediately following the = sign: src={avatar}
React allows writing HTML-like markup inside JavaScript files, combining rendering logic and content. The parser provides guidance on correcting invalid markup through console messages. Most codebases use JSX for its conciseness and integration with React's architecture.
<textarea> elements implement both controlled and uncontrolled behavior paradigms. The component's default height is specified in average character heights (defaulting to 2), with three available wrapping modes: 'hard', 'soft', or 'off'. Default and controlled behavior differ significantly. A text area cannot simultaneously function in both modes and cannot transition between them during its lifespan. Controlled instances require an onChange event handler to update their backing value synchronously. Rendering options include the standard <textarea> tag, with customizable default sizes via rows and cols attributes. The resize property can be set to none to disable resizing, and accessibility is enhanced by nesting the <textarea> within a <label>. Component instances should use unique IDs generated with the useId hook. For uncontrolled operations, the defaultValue attribute sets the initial value instead of children content. The component supports a variety of attributes including autoComplete (on/off), disabled status, and form association. The value of the <textarea> is managed through props—controlled inputs require both value and onChange handlers, while uncontrolled inputs use defaultValue. Interactive features include selection management and event handling. The placeholder attribute provides dimmed text when the area is empty, while readOnly makes the text area uneditable. The required attribute ensures form submission depends on the textarea containing a value. The wrap attribute controls text wrapping with options: 'hard', 'soft', or 'off' (default). Event handlers encompass onChange for value changes, onInvalid for validation failures, and onSelect for selection events. The onChange handler behaves similarly to the browser's input event, firing immediately on user input changes including keystrokes. Additional handlers include capture-phase versions of onChange, onInput, and onInvalid, along with pre-existing browser events like onSelect that React extends to include empty selection and edit-based changes. ## Conditional Rendering in JSX React's JSX extends JavaScript with HTML-like syntax, allowing developers to integrate rendering logic and markup within components while maintaining separation between unrelated elements. The majority of HTML attributes convert to camelCase property names in JSX, though some reserved words remain unchanged. For example, stroke-width becomes strokeWidth and class becomes className. This convention enhances code readability while maintaining compatibility with JavaScript syntax. Developers can convert existing HTML and SVG code to JSX using a converter tool or manual translation. The process requires attention to JSX's specific rules, particularly the proper use of curly braces for JavaScript integration. The parser provides guidance through the browser console when parsing invalid JSX, helping developers correct their markup. The JSX syntax requires each file to return a single root element, typically wrapped in a
or <React.Fragment> for multiple elements to avoid leaving behind browser-specific HTML traces. All tags must be explicitly closed, including self-closing tags like , which become in JSX syntax. The parser offers helpful console messages to guide developers towards correct syntax and structure. Most JavaScript properties and expressions can be directly incorporated into JSX using curly braces. These include passing strings with quotes (e.g., src="https://i.imgur.com/7vQD0fPs.jpg"), referencing JavaScript variables (e.g., alt={description}), and making function calls within JSX (e.g., <button onClick={handleClick}>). Curly braces are used both inside JSX tags (e.g.,
) and as attributes immediately following the = sign (e.g., src={avatar}).