Cos'è la conversione da HTML a JSX?
La conversione da HTML a JSX è il processo di trasformazione del markup HTML standard in sintassi JSX che i componenti React possono renderizzare. JSX è simile all'HTML ma segue le convenzioni di denominazione e le regole di JavaScript. Attributi come class diventano className, for diventa htmlFor, e le stringhe di stile inline vengono sostituite con oggetti JavaScript. Queste modifiche sono necessarie perché JSX viene compilato in chiamate a React.createElement(), dove i nomi degli attributi devono corrispondere ai nomi delle proprietà dell'API DOM anziché ai nomi degli attributi HTML.
La mappatura tra gli attributi HTML e le prop JSX è definita dalla documentazione degli elementi DOM di React. React usa il camelCase per gli attributi composti da più parole (tabindex diventa tabIndex, maxlength diventa maxLength) perché gli identificatori JavaScript non possono contenere trattini. I tag autochiudenti come <img>, <br> e <input> devono includere uno slash finale in JSX (<img />) poiché JSX segue le regole XML, dove ogni tag deve essere chiuso esplicitamente.
htmlToJsxContent.whatBody3
Perché usare un convertitore HTML in JSX?
Rinominare manualmente gli attributi e riscrivere le stringhe di stile su decine di elementi HTML è lento e soggetto a errori. Un convertitore gestisce ogni trasformazione in una sola operazione, permettendoti di incollare HTML da qualsiasi sorgente e ottenere JSX valido in pochi secondi.
Casi d'uso del convertitore HTML in JSX
Tabella di riferimento degli attributi HTML→JSX
La tabella seguente elenca gli attributi HTML che cambiano quando vengono convertiti in JSX. Gli attributi non elencati qui (id, src, href, alt, placeholder, ecc.) rimangono invariati perché i loro nomi HTML corrispondono già ai nomi delle proprietà dell'API DOM.
| Attributo HTML | Prop JSX | Note |
|---|---|---|
| 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 |
Conversione degli stili inline: HTML vs JSX
Gli stili inline sono la parte più soggetta a errori nella conversione da HTML a JSX perché cambiano sia il formato del valore sia i nomi delle proprietà:
<div style="background-color: #fff; font-size: 14px; margin-top: 10px;">
<div style={{
backgroundColor: '#fff',
fontSize: '14px',
marginTop: 10
}}>Esempi di codice
Questi esempi mostrano come convertire HTML in JSX a livello di codice in diversi linguaggi e ambienti. Ognuno copre la rinomina degli attributi, la conversione degli stili e la gestione dei tag autochiudenti.
// 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>
}