JSX Attributes in React JS Tutorial 🎯

beginner
22 min

JSX Attributes in React JS Tutorial 🎯

Welcome back to CodeYourCraft! Today, we're diving into JSX attributes - an essential part of React JS that helps us manipulate HTML elements and attributes in a declarative manner.

Understanding JSX Attributes 📝

JSX stands for JavaScript XML, and it's a syntax extension for JavaScript. One of its key features is the ability to create HTML-like elements and assign attributes to them.

Here's a simple example of a React component using JSX attributes:

jsx
import React from 'react'; class MyComponent extends React.Component { render() { return <div id="my-div" className="my-class">Hello, World!</div>; } }

In this example, we have created a div element with an id and a className. The text Hello, World! is the content of the div.

Assigning Attributes 💡

JSX attributes are named properties in JavaScript objects, with the name prefixed by a double underscore (__). The value of the attribute is the value of the property.

Here's a more detailed example:

jsx
import React from 'react'; class MyComponent extends React.Component { render() { const myAttributes = { id: 'my-id', className: 'my-class', style: { color: 'red', fontSize: '2em' } }; return <div {...myAttributes}>Hello, World!</div>; } }

In this example, we have created an object myAttributes with three properties: id, className, and style. The spread operator (...) is used to pass these properties to the div element.

Special Attributes 📝

There are some special attributes in JSX that are worth noting:

  1. className: This is used to set the class of an HTML element. Note the spelling - React uses className instead of class.

  2. style: This is used to set the inline styles of an HTML element. The value should be an object with style properties.

  3. key: This is used to identify each item in a list. It helps React identify which items have changed, are added, or are removed.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `id` attribute in JSX?

In the next lesson, we'll dive deeper into styling components in React using CSS-in-JS. Stay tuned! 🚀