¿Qué es la conversión de HTML a JSX?
La conversión de HTML a JSX es el proceso de transformar marcado HTML estándar en sintaxis JSX que los componentes de React pueden renderizar. JSX se parece al HTML pero sigue las convenciones de nomenclatura y las reglas de JavaScript. Atributos como class se convierten en className, for se convierte en htmlFor, y los estilos en línea como cadenas se reemplazan con objetos JavaScript. Estos cambios son necesarios porque JSX compila a llamadas React.createElement(), donde los nombres de atributo deben coincidir con los nombres de propiedad de la API del DOM en lugar de los nombres de atributo HTML.
La correspondencia entre atributos HTML y props JSX está definida por la documentación de elementos del DOM de React. React usa camelCase para atributos de varias palabras (tabindex se convierte en tabIndex, maxlength en maxLength) porque los identificadores de JavaScript no pueden contener guiones. Las etiquetas de cierre automático como <img>, <br> e <input> deben incluir una barra diagonal final en JSX (<img />) ya que JSX sigue las reglas XML donde cada etiqueta debe cerrarse explícitamente.
htmlToJsxContent.whatBody3
¿Por qué usar un conversor de HTML a JSX?
Renombrar atributos manualmente y reescribir cadenas de estilo en decenas de elementos HTML es lento y propenso a errores. Un conversor gestiona todas las transformaciones de una vez, permitiéndote pegar HTML de cualquier fuente y obtener JSX válido en segundos.
Casos de uso de HTML a JSX
Referencia de correspondencia de atributos HTML a JSX
La tabla a continuación lista los atributos HTML que cambian al convertirse a JSX. Los atributos no listados aquí (id, src, href, alt, placeholder, etc.) permanecen sin cambios porque sus nombres HTML ya coinciden con los nombres de propiedad correspondientes de la API del DOM.
| Atributo HTML | Prop JSX | Notas |
|---|---|---|
| class | className | Reserved word in JavaScript |
| for | htmlFor | Reserved word in JavaScript |
| tabindex | tabIndex | camelCase convention |
| readonly | readOnly | camelCase convention |
| maxlength | maxLength | camelCase convention |
| minlength | minLength | camelCase convention |
| cellpadding | cellPadding | camelCase convention |
| cellspacing | cellSpacing | camelCase convention |
| rowspan | rowSpan | camelCase convention |
| colspan | colSpan | camelCase convention |
| enctype | encType | camelCase convention |
| autocomplete | autoComplete | camelCase convention |
| autofocus | autoFocus | camelCase convention |
| autoplay | autoPlay | camelCase convention |
| contenteditable | contentEditable | camelCase convention |
| crossorigin | crossOrigin | camelCase convention |
| novalidate | noValidate | camelCase convention |
| allowfullscreen | allowFullScreen | camelCase convention |
| spellcheck | spellCheck | camelCase convention |
| http-equiv | httpEquiv | Hyphen removed, camelCase |
| onclick | onClick | Event handler camelCase |
| onchange | onChange | Event handler camelCase |
| onsubmit | onSubmit | Event handler camelCase |
Conversión de estilos en línea: HTML vs JSX
Los estilos en línea son la parte más propensa a errores de la conversión de HTML a JSX porque cambian tanto el formato del valor como los nombres de las propiedades:
<div style="background-color: #fff; font-size: 14px; margin-top: 10px;">
<div style={{
backgroundColor: '#fff',
fontSize: '14px',
marginTop: 10
}}>Ejemplos de código
Estos ejemplos muestran cómo convertir HTML a JSX de forma programática en diferentes lenguajes y entornos. Cada uno cubre el renombrado de atributos, la conversión de estilos y el tratamiento de etiquetas de cierre automático.
// Simple attribute conversion using string replacement
function htmlToJsx(html) {
return html
.replace(/\bclass=/g, 'className=')
.replace(/\bfor=/g, 'htmlFor=')
.replace(/\btabindex=/g, 'tabIndex=')
.replace(/<!--([\s\S]*?)-->/g, '{/*$1*/}')
}
htmlToJsx('<div class="box" tabindex="0"><!-- note --></div>')
// → '<div className="box" tabIndex="0">{/* note */}</div>'import parse from 'html-react-parser'
// Parse HTML string into React elements (handles all JSX rules)
const element = parse('<div class="card"><img src="photo.jpg" alt="Photo"></div>')
// Returns: React.createElement('div', { className: 'card' },
// React.createElement('img', { src: 'photo.jpg', alt: 'Photo' }))
// With custom element replacement
const options = {
replace(domNode) {
if (domNode.name === 'img') {
return <OptimizedImage src={domNode.attribs.src} alt={domNode.attribs.alt} />
}
}
}
const custom = parse('<img src="photo.jpg" alt="Photo">', options)from bs4 import BeautifulSoup
import re
ATTR_MAP = {
'class': 'className', 'for': 'htmlFor',
'tabindex': 'tabIndex', 'readonly': 'readOnly',
'maxlength': 'maxLength', 'autocomplete': 'autoComplete',
}
def html_to_jsx(html: str) -> str:
"""Convert HTML attribute names to JSX equivalents."""
for html_attr, jsx_attr in ATTR_MAP.items():
html = re.sub(rf'\b{html_attr}=', f'{jsx_attr}=', html)
# Convert HTML comments to JSX comments
html = re.sub(r'<!--(.*?)-->', r'{/*\1*/}', html)
return html
print(html_to_jsx('<label for="email" class="field">Email</label>'))
# → '<label htmlFor="email" className="field">Email</label>'package main
import (
"fmt"
"strings"
)
var attrMap = map[string]string{
"class=": "className=",
"for=": "htmlFor=",
"tabindex=": "tabIndex=",
"readonly": "readOnly",
}
func htmlToJSX(html string) string {
result := html
for old, new := range attrMap {
result = strings.ReplaceAll(result, old, new)
}
// Convert comments
result = strings.ReplaceAll(result, "<!--", "{/*")
result = strings.ReplaceAll(result, "-->", "*/}")
return result
}
func main() {
html := `<div class="wrapper"><input readonly tabindex="1"></div>`
fmt.Println(htmlToJSX(html))
// → <div className="wrapper"><input readOnly tabIndex="1"></div>
}