REACT

JSX Basics ?


JSX (JavaScript XML) is a syntax extension for JavaScript commonly used with React to describe what the UI should look like. Here are the basics:


1. What is JSX?

JSX allows you to write HTML-like code directly in your JavaScript files. This makes it easier to visualize the UI structure and helps in building the component hierarchy.


2. Embedding Expressions

You can embed JavaScript expressions inside JSX by wrapping them in curly braces {}.
 

Example:

const name = 'World';
const element = <h1>Hello, {name}!</h1>;

 

3. Attributes in JSX

JSX attributes are similar to HTML attributes but follow camelCase naming conventions for JavaScript compatibility.

 

Example

const element = <img src="image.jpg" alt="Image description" />;

 

4. Nesting Elements

You can nest elements inside other elements just like in HTML.
 

const element = (
 <div>
   <h1>Hello, World!</h1>
   <p>This is a paragraph.</p>
 </div>
);

 

5. JSX is an Expression

JSX compiles down to regular JavaScript objects using tools like Babel. This means you can use JSX inside functions, loops, and conditionals.
 

function greeting(user) {
 if (user) {
   return <h1>Hello, {user.name}!</h1>;
 }
 return <h1>Hello, Stranger!</h1>;
}

 

6. Specifying Children

You can specify child elements either as nested elements or as an array of elements.
 

Example:

const element = (
 <div>
   <h1>Hello, World!</h1>
   <p>This is a paragraph.</p>
 </div>
);

// Or as an array
const element = (
 <div>
   {[<h1 key="1">Hello, World!</h1>, <p key="2">This is a paragraph.</p>]}
 </div>
);

 

7. Components in JSX

Components can be defined as JavaScript functions or classes and used within JSX.
 


Functional Component

function Welcome(props) {
 return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
Class Component
class Welcome extends React.Component {
 render() {
   return <h1>Hello, {this.props.name}</h1>;
 }
}

const element = <Welcome name="Sara" />;

 

8. Differences from HTML

There are a few key differences between JSX and HTML:

Class vs. className: Use className instead of class.
Self-closing Tags: Tags like <img /> must be self-closed.
camelCase Property Naming: Use camelCase for event handlers (e.g., onClick).
 

Example Component

import React from 'react';
import ReactDOM from 'react-dom';

function App() {
 return (
   <div>
     <h1>Welcome to React</h1>
     <p>This is a simple React component using JSX.</p>
   </div>
 );
}

ReactDOM.render(<App />, document.getElementById('root'));