Converting Vanilla JavaScript to JSX involves making changes to the code structure and syntax to work with React. Here’s a simple guide:
1. HTML to JSX
JSX uses XML-like syntax, so you must ensure proper casing, closing of all tags, and correct attribute names:
Example:
HTML:
<div class="container">
<h1>Hello World</h1>
<input type="text" />
</div>
JSX:
<div className="container">
<h1>Hello World</h1>
<input type="text" />
</div>
Key Changes:
class
becomesclassName
.- Use camelCase for attributes like
onclick
→onClick
,tabindex
→tabIndex
, etc. - Ensure all tags are properly closed (e.g.,
<input />
).
2. Inline JavaScript
Use {}
to include dynamic JavaScript inside JSX.
Example:
Vanilla JS:
const name = "John";
document.getElementById("root").innerHTML = `
<h1>Hello, ${name}</h1>
`;
JSX:
const name = "John";
return <h1>Hello, {name}</h1>;
3. Event Handlers
In JSX, event handlers use camelCase and take functions directly.
Example:
Vanilla JS:
document.getElementById("btn").addEventListener("click", () => {
console.log("Clicked!");
});
JSX:
<button onClick={() => console.log("Clicked!")}>Click Me</button>
4. Rendering the UI
React uses ReactDOM.render
(or createRoot
for modern React).
Example:
Vanilla JS:
document.getElementById("root").innerHTML = "<h1>Hello World</h1>";
JSX:
import React from "react";
import ReactDOM from "react-dom";
ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"));
5. Loops
Instead of for
or forEach
, JSX often uses map
to loop over data.
Example:
Vanilla JS:
const items = ["Apple", "Banana", "Cherry"];
let listHTML = "";
items.forEach((item) => {
listHTML += `<li>${item}</li>`;
});
document.getElementById("list").innerHTML = listHTML;
JSX:
const items = ["Apple", "Banana", "Cherry"];
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
6. Conditional Rendering
Use ternary operators or &&
for conditional rendering in JSX.
Example:
Vanilla JS:
const isLoggedIn = true;
document.getElementById("root").innerHTML = isLoggedIn
? "<h1>Welcome Back!</h1>"
: "<h1>Please Sign In</h1>";
JSX:
const isLoggedIn = true;
return <h1>{isLoggedIn ? "Welcome Back!" : "Please Sign In"}</h1>;