JSX (JavaScript XML) is an extension of JavaScript that allows you to write HTML directly within React. When using JSX, attributes are similar to HTML attributes but follow different conventions, particularly in their naming and usage.
JSX attributes are used to pass information to elements and components, similar to how HTML attributes work. However, there are some differences in how these attributes are written and used in JSX:
{}.Here’s an example of using JSX attributes in a React component:
return (
<>
<h2 contentEditable="true">React App</h2>
</>
);
In this example:
contentEditable attribute is used, which is similar to the contenteditable attribute in HTML but written in camelCase as contentEditable.Here are some common JSX attributes and their HTML counterparts:
className instead of classhtmlFor instead of foronClick instead of onclicktabIndex instead of tabindexreadOnly instead of readonlyLet's see an example that uses several JSX attributes:
return (
<>
<button className="btn-primary" onClick={handleClick} disabled={isDisabled}>
Click Me
</button>
<label htmlFor="username">Username:</label>
<input id="username" type="text" readOnly={true} tabIndex="1" />
</>
);
In this example:
button element uses className, onClick, and disabled attributes.label element uses the htmlFor attribute.input element uses the id, type, readOnly, and tabIndex attributes.disabled, checked, readOnly) if the value is true. Use curly braces for dynamic boolean values (e.g., disabled={isDisabled}).return (
<>
<input type="checkbox" checked /> {/* Always checked */}
<input type="checkbox" checked={isChecked} /> {/* Dynamically checked */}
</>
);
Understanding and correctly using JSX attributes is fundamental in React development. It ensures that your components behave as expected and follow React's conventions.