Lecture Notes Of Day 3: JSX - JavaScript XML

Rashmi Mishra
0

 

Lecture Notes Of Day 3: JSX - JavaScript XML 

Objective: Learn the basics of JSX (JavaScript XML) and how it integrates with JavaScript code. Outcome: Write JSX code and understand how it gets converted to JavaScript.

ChatGPT said:

ChatGPT

Day 3: JSX - JavaScript XML


Objective:

Learn the basics of JSX (JavaScript XML) and how it integrates with JavaScript code.

Outcome:

By the end of this lesson, students should be able to write JSX code and understand how it is converted into JavaScript that the browser can interpret.


1. What is JSX?

  • Definition: JSX stands for JavaScript XML. It’s a syntax extension for JavaScript that allows you to write HTML-like code directly within JavaScript.
  • Usage in React: JSX is widely used in React to define what the UI should look like. Rather than separating HTML and JavaScript code, JSX enables a seamless way to combine both in one place.
  • Why Use JSX?:
    • Readability: JSX makes it easier to understand the structure and layout of a component at a glance.
    • Integration: Allows us to use JavaScript logic within HTML structures.

2. Writing Basic JSX

JSX allows us to write HTML-like syntax directly within JavaScript functions, which React then renders to the DOM. Here’s an example:

javascript

Copy code

const greeting = <h1>Hello, World!</h1>;

  • In this example, <h1>Hello, World!</h1> looks like HTML, but it is actually JSX.
  • JSX must be contained within a single parent element, so grouping multiple JSX elements requires enclosing them in a wrapper element, like a <div>, or a special React Fragment.

3. How JSX Integrates with JavaScript

In JSX, you can use JavaScript expressions by placing them within curly braces { }. Here’s an example:

javascript

Copy code

const name = "Alice";

const greeting = <h1>Hello, {name}!</h1>;

  • Curly Braces { }: The curly braces tell React that this part is JavaScript, not text.
  • Expressions Only: You can use JavaScript expressions (like variables, functions, and calculations) inside curly braces but not statements like if or for directly.

Example: Combining Text with JavaScript Expression

javascript

Copy code

const age = 25;

const message = <p>I am {age} years old.</p>;


4. JSX is Not HTML

Although JSX looks like HTML, there are some key differences:

  • Class vs. ClassName: In HTML, we use class to assign CSS classes. In JSX, we use className to avoid conflicts with JavaScript's class keyword.

javascript

Copy code

const element = <h1 className="header">Hello!</h1>;

  • Self-Closing Tags: Like HTML, tags with no children must be self-closed. For example, <img /> or <input />.
  • Camel Case Properties: JSX uses camelCase for naming properties (e.g., onClick instead of onclick).

5. JSX is Converted to JavaScript

  • Behind the Scenes: When you write JSX, it is not directly readable by browsers. JSX is converted into regular JavaScript by a compiler, like Babel, before being rendered.
  • React.createElement: Each JSX element is transformed into a call to React.createElement, which constructs the virtual DOM objects.

Example: JSX and Its JavaScript Equivalent

javascript

Copy code

// JSX Code

const element = <h1 className="header">Hello, React!</h1>;

 

// Compiled JavaScript Code

const element = React.createElement(

  'h1',

  { className: 'header' },

  'Hello, React!'

);


6. Embedding JavaScript Logic in JSX

In JSX, we can execute small JavaScript expressions directly within the JSX structure using curly braces.

Example: Calculations and Conditions in JSX

javascript

Copy code

const a = 5;

const b = 10;

 

const sum = <p>The sum is {a + b}.</p>; // Output: The sum is 15

Conditional Rendering Example with Ternary Operator:

javascript

Copy code

const isLoggedIn = true;

const message = <h1>{isLoggedIn ? "Welcome back!" : "Please log in."}</h1>;


7. Styling JSX Elements

You can style JSX elements in two main ways: using inline styles or CSS classes.

1.  Inline Styles: Inline styles in JSX are written as JavaScript objects. Property names are written in camelCase.

javascript

Copy code

const style = { color: 'blue', fontSize: '20px' };

const element = <h1 style={style}>Styled Text</h1>;

2.  CSS Classes: Use the className attribute to apply CSS classes to JSX elements.

javascript

Copy code

const element = <h1 className="my-class">Text with CSS Class</h1>;


8. JSX Fragments

Fragments let you group multiple elements without adding extra nodes to the DOM. This is useful for keeping the output clean when grouping child elements in a single parent.

Example Using React.Fragment:

javascript

Copy code

return (

  <React.Fragment>

    <h1>Title</h1>

    <p>Description text goes here.</p>

  </React.Fragment>

);

You can also use a shorthand syntax:

javascript

Copy code

return (

  <>

    <h1>Title</h1>

    <p>Description text goes here.</p>

  </>

);


9. JSX Best Practices

  • Keep JSX Simple and Clear: Avoid deeply nested elements to keep the code readable.
  • Use Meaningful Variable Names: Name your JSX elements and components descriptively.
  • Avoid Inline Complex Logic: Keep calculations, functions, or complex logic out of JSX to improve readability.

Summary and Key Takeaways

  • JSX (JavaScript XML) allows us to write HTML-like syntax within JavaScript.
  • JSX is compiled to JavaScript and transformed to React.createElement calls, which create virtual DOM objects.
  • Curly braces { } allow you to embed JavaScript expressions inside JSX.
  • JSX and HTML have differences: use className instead of class, camelCase for attributes, and self-closing tags.
  • Fragments enable grouping of elements without adding unnecessary parent elements to the DOM.

Practice

1.  Create a component that displays a greeting message using JSX.

2.  Use an inline style to change the color of text within a JSX element.

3.  Try using conditional rendering to display different messages based on a variable’s value.

By understanding JSX, students can now comfortably build components that blend HTML structure with JavaScript, creating interactive and dynamic web applications.


Post a Comment

0Comments

Post a Comment (0)