🛠️ToolsShed

HTML to JSX

Convert HTML markup to JSX syntax for React. Transforms attributes, inline styles, and void elements automatically.

Conversions applied:

  • classclassName
  • forhtmlFor
  • style="..."style={{...}}
  • Void elements (br, hr, img, input) self-closed
  • HTML comments converted to {/* */}

Sıkça Sorulan Sorular

Kod Uygulaması

import re

def html_to_jsx(html: str) -> str:
    jsx = html
    # class -> className
    jsx = re.sub(r'\bclass=', 'className=', jsx)
    # for -> htmlFor
    jsx = re.sub(r'\bfor=', 'htmlFor=', jsx)
    # HTML comments to JSX
    jsx = re.sub(r'<!--(.*?)-->', r'{/*\1*/}', jsx, flags=re.DOTALL)
    # Self-close void elements
    void_elements = ['area','base','br','col','embed','hr','img','input',
                     'link','meta','param','source','track','wbr']
    for tag in void_elements:
        jsx = re.sub(
            rf'<{tag}(\s[^>]*)?>',
            lambda m: m.group(0)[:-1] + ' />' if not m.group(0).endswith('/>') else m.group(0),
            jsx, flags=re.IGNORECASE
        )
    return jsx

html = '<div class="container"><br><img src="x.png" alt=""></div>'
print(html_to_jsx(html))
# <div className="container"><br /><img src="x.png" alt="" /></div>

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.