HTML to JSX
What is an Html To Jsx?
JSX looks like HTML but follows JavaScript rules, so pasting HTML from a template, a design tool or a Bootstrap example into a React component usually produces errors. This converter rewrites HTML into valid JSX automatically.
How to use it
- Paste the HTML snippet.
- Copy the JSX output into your component's return statement.
What changes
classbecomesclassName, andforbecomeshtmlFor, because both are reserved words in JavaScript.- Inline styles become objects:
style='margin-top: 8px'becomesstyle={{ marginTop: '8px' }}. - Void elements are self-closed:
<img>,<br>and<input>become<img />,<br />,<input />. - Event and other attributes are camelCased:
onclickbecomesonClick,tabindexbecomestabIndex. - HTML comments become JSX comments:
{/* ... */}.
Example
Input:
<label for='email' class='label'>Email</label>
<input id='email' type='email' style='width: 100%'>Output:
<label htmlFor='email' className='label'>Email</label>
<input id='email' type='email' style={{ width: '100%' }} />After converting
- Wrap multiple top-level elements in a fragment
<>...</>. - Replace inline
onClickstrings with real function handlers. - Convert form fields to controlled components with
valueandonChange, or usedefaultValue. aria-*anddata-*attributes keep their hyphenated names.
Frequently Asked Questions
Why does React use className instead of class?
JSX compiles to JavaScript, where class is a reserved word. React uses the DOM property name className.
How are inline styles converted?
Style strings become JavaScript objects with camelCased property names, such as marginTop.
Do data and aria attributes change?
No. data- and aria- attributes keep their hyphenated names in JSX.
Why do I get an error about adjacent JSX elements?
A component must return a single root. Wrap the elements in a fragment.
Is the converted JSX also valid for Preact or Solid?
Mostly yes. Preact accepts className and also plain class. Solid uses class rather than className, so adjust attribute names for Solid.
Does it convert SVG attributes?
Hyphenated SVG attributes such as stroke-width become camelCase like strokeWidth, which React expects.