From HTML to JSX: Bridging the Gap
Writing JSX code in reactjs
import React from 'react'; function MyComponent() { return ( <div> <h1>Welcome to My Component</h1> <p>This is a paragraph.</p> </div> ); }
JSX and HTML Differences
Syntax and Attribute Names:
HTML attributes use kebab-case (e.g., class, id, src).
JSX attributes use camelCase (e.g., className, id, src).
HTML elements are written in lowercase (e.g., <div>, <p>, <span>).
JSX elements and component names start with an uppercase letter (e.g., <MyComponent>, <CustomButton>).
Class vs. ClassName:
In HTML, the class attribute is used to define CSS classes for an element.
In JSX, the className attribute is used instead of class to avoid conflicts with the JavaScript class keyword.
Self-closing Tags:
In HTML, certain elements like <img>, <br>, and <input> can be self-closed (<img src="..." />).
In JSX, self-closing tags must always end with /> (e.g., <img src="..." />).
Inline Styles:
In HTML, you define styles using the style attribute with CSS syntax (e.g., <div style="color: red;">Hello</div>).
In JSX, the style attribute expects a JavaScript object with CSS properties written in camelCase (e.g., <div style={{ color: 'red', fontSize: "15px" }}>Hello</div>).
Comments:
HTML comments are written as <!-- Comment -->.
JSX comments are written within curly braces and two forward slashes ({/* Comment */}).
It's important to note that JSX is not HTML but a syntactic extension of JavaScript. The main purpose of JSX is to allow you to write declarative and component-based UI code in a more intuitive and concise manner. JSX gets transpiled into JavaScript code that creates React elements and manages the component's lifecycle.
While there are differences between JSX and HTML, JSX still maintains a familiar HTML-like structure, making it easier for developers to transition and work with React components.