JSX Attributes
You can set HTML attributes the same way you do in HTML, but with React there are a few differences and enhancements to HTML.
JavaScript expressions as HTML attributes or props
As we've discussed previously, you can embed JavaScript expressions in JSX with the curly braces. This also follows for setting HTML attributes or React component props.
HTML Attributes vs Component props
When dealing with elements in React, it's typical to refer to the attributes set as props. However sometimes it's important to distinguish between setting native HTML attributes, and setting custom React component props. At the end of the day, the syntax is the same. Just remember that HTML attributes are not defined by the React library, and React has made some changes here.
Class vs className
class
is a reserved word in JavaScript, so it cannot be used to directly refer to the HTML attribute class. You must use className
instead. This is all you need to know. Otherwise, it behaves the same way: a string referring to a CSS class. See the example's styles.css
defining the css class we have set here.
Event handlers must be camelCased
In HTML, the onclick
attribute is used to specify a string of JavaScript that runs on click. With React, the attribute is onClick
, and you must pass in a JavaScript function. This follows for all other HTML event handlers: onKeyDown
, onDrag
, etc.
We'll talk more about custom React props next.
const myTask = "Swab the deck!"; const URL = "https://react.school"; function CustomComponent(props) { return ( <div style={{ border: "1px solid gray", padding: "20px" }}> <div>{props.title}</div> <div>{props.description}</div> </div> ); } export default function App() { function sayHello() { alert("hello"); } const spreadAttributes = { title: "Title set through Spread", description: "Description 2", }; return ( <> <h1> 🏴☠️ The Captain's Tasks </h1> <p> Managing my tasks at sea </p> {/* JavaScript expressions as HTML attributes */} <a href={URL}>This is a link</a> {/* className, not class */} <div className="red-text">Red text</div> {/* event handlers must be camelCased */} <div onClick={sayHello}>Click me</div> {/* Setting component props */} <CustomComponent title="Title" description="Description" /> {/* Spread operator setting props */} <CustomComponent {...spreadAttributes} /> </> ); }