HTML to JSX 변환이란 무엇인가요?
HTML to JSX 변환은 표준 HTML 마크업을 React 컴포넌트가 렌더링할 수 있는 JSX 문법으로 변환하는 과정입니다. JSX는 HTML과 유사하게 보이지만 JavaScript 명명 규칙과 규칙을 따릅니다. class와 같은 속성은 className이 되고, for는 htmlFor가 되며, 인라인 style 문자열은 JavaScript 객체로 교체됩니다. JSX는 React.createElement() 호출로 컴파일되기 때문에 이러한 변경이 필요합니다. 속성 이름은 HTML 속성 이름이 아닌 DOM API 속성 이름과 일치해야 합니다.
HTML 속성과 JSX props 간의 매핑은 React의 DOM 요소 문서에 정의되어 있습니다. React는 다중 단어 속성에 camelCase를 사용합니다(tabindex는 tabIndex, maxlength는 maxLength). JavaScript 식별자에는 하이픈이 포함될 수 없기 때문입니다. <img>, <br>, <input>과 같은 자기 닫힘 태그는 JSX에서 끝에 슬래시를 포함해야 합니다(<img />). JSX는 모든 태그를 명시적으로 닫아야 하는 XML 규칙을 따르기 때문입니다.
htmlToJsxContent.whatBody3
HTML to JSX 변환기를 사용하는 이유
수십 개의 HTML 요소에서 속성을 수동으로 이름 변경하고 style 문자열을 재작성하는 것은 느리고 오류가 발생하기 쉽습니다. 변환기는 모든 변환을 한 번에 처리하므로 어떤 소스의 HTML이든 붙여넣기만 하면 몇 초 안에 유효한 JSX를 얻을 수 있습니다.
HTML to JSX 사용 사례
HTML to JSX 속성 매핑 참조
아래 표는 JSX로 변환할 때 바뀌는 HTML 속성을 나열합니다. 여기에 없는 속성(id, src, href, alt, placeholder 등)은 HTML 이름이 이미 해당 DOM API 속성 이름과 일치하므로 그대로 유지됩니다.
| HTML 속성 | JSX Prop | 참고 |
|---|---|---|
| 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 |
인라인 스타일 변환: HTML vs JSX
인라인 스타일은 값의 형식과 속성 이름이 모두 바뀌기 때문에 HTML to JSX 변환에서 가장 오류가 발생하기 쉬운 부분입니다:
<div style="background-color: #fff; font-size: 14px; margin-top: 10px;">
<div style={{
backgroundColor: '#fff',
fontSize: '14px',
marginTop: 10
}}>코드 예제
아래 예제는 다양한 언어와 환경에서 HTML을 JSX로 프로그래밍 방식으로 변환하는 방법을 보여줍니다. 각 예제는 속성 이름 변경, 스타일 변환, 자기 닫힘 태그 처리를 다룹니다.
// 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>
}