JSX in React

JSX in React

What is JSX?

  • It is a shorthand for JavaScript XML which is inlining XML and HTML in JavaScript.

  • JSX full form is JavaScript XML, which allows us to write HTML in React. JSX makes it easier for us to write and add HTML to React.

Rules For Writing JSX

  • Self-closing tags must have a forward slash at the end, unlike normal HTML

  • When we use curly braces ie {} only javascript should be written inside these braces

  • Tags which have both opening and ending should have both else we will get an error

  • We should always return a single element. If we have multiple element returns then we will get an error, to overcome this we need to use

<> </> or <react.fragment> <react.fragment/>

  • While rendering the fragment is removed from the react DOM

  • NULL, UNDEFINED, TRUE re not rendered by React

Drawback Of Using JSX

  • HTML elements must be correct and properly closed else JSX throws an error.

  • The browser cannot read the syntax of JSX, as it uses ES6 classes and browsers didn’t understand ES6 classes so first, it needs to convert ES6 into ES5. Later in 2014, Babelwas introduced to solve this problem and help browsers to read JSX code by converting it into plain JS.

Summary

  • JSX stands for JavaScript XML.

  • JSX is a language that allows you to mix JavaScript and HTML-like tags to define user interface (UI) elements and their functionality.

  • JSX is an extension for JavaScript that allows for writing what looks like HTML and XML in our JavaScript.

  • JSX is a shorthand for calling React.createElement() to create elements and components.

  • JSX looks like HTML and offers a friendly syntax for creating DOM elements.

  • JSX accepts any valid JavaScript expression inside curly braces{}.

Inline-Styles in JSX

  1. We give inline styles in jsx by creating an object which has a key- value pair which represents the style and then we can add javascript using {}

Props in react

  1. Props are nothing but abbreviations for properties

  2. They are bascially parameter passed into functional components

  3. As functional components are basically function in simple language, whenever we pass a parameter to a function we call it a prop

Paranthesis vs Curly Braces

In React, both parentheses ( ) and curly braces { } have different uses and meanings.

  1. Parentheses ( ):

    • In JSX: Parentheses are used to wrap an expression within JSX. This is typically used when rendering or evaluating an expression within JSX tags. For example:

        return (
          <div>
            <h1>{title}</h1>
            <p>{name}</p>
          </div>
        );
      

      Here, the expressions {title} and {name} are wrapped in parentheses within the JSX tags to evaluate and render their values.

    • In JavaScript: Parentheses are used for grouping expressions and controlling the order of operations in JavaScript. They are used to change the default precedence of operators. For example:

        const result = (2 + 3) * 4; // result is 20
      
  2. Curly braces { }:

    • In JSX: Curly braces are used to embed JavaScript expressions or variables within JSX. This allows you to dynamically render values, perform calculations, or execute functions. For example:

        return (
          <div>
            <h1>{`${firstName} ${lastName}`}</h1>
            <p>{age + 5}</p>
            <button onClick={() => handleClick()}>Click me</button>
          </div>
        );
      

      Here, the expressions ${firstName} ${lastName}, age + 5, and the arrow function within onClick are all enclosed in curly braces to embed JavaScript code within JSX.

    • In JavaScript: Curly braces are used to define blocks of code, such as for functions, loops, or conditional statements. They define the scope of variables and control the flow of code execution. For example:

        function myFunction() {
          // Code block
        }
      
        if (condition) {
          // Code block
        }
      

To summarize, parentheses ( ) are primarily used in JSX to wrap expressions, while curly braces { } are used to embed JavaScript code within JSX and define blocks of code in JavaScript. Understanding the context and usage of parentheses and curly braces is important for proper syntax and behavior in React and JavaScript.

Yes, in React, anything inside curly braces { } within JSX is treated as JavaScript code. This allows you to embed JavaScript expressions, variables, functions, or any other valid JavaScript code directly within JSX.

When you use curly braces { } in JSX, React evaluates the JavaScript code inside them and renders the result as part of the JSX expression.

Here are some examples of using curly braces in React:

  1. Embedding variables:

     const name = 'John Doe';
     return <h1>{name}</h1>;
    

    The variable name is wrapped in curly braces within JSX, and its value is dynamically rendered.

  2. Evaluating expressions:

     const age = 30;
     return <p>Next year, I will be {age + 1} years old.</p>;
    

    The expression age + 1 is enclosed in curly braces, and the result is evaluated and rendered within the JSX element.

  3. Invoking functions:

     function formatName(firstName, lastName) {
       return `${firstName} ${lastName}`;
     }
     return <p>{formatName('John', 'Doe')}</p>;
    

    The formatName function is called within curly braces, and its return value is rendered as part of the JSX.

By using curly braces, you can seamlessly integrate JavaScript code and logic within JSX, enabling dynamic rendering and the execution of JavaScript operations within your React components.

However, it's important to note that only valid JavaScript code can be used within curly braces in JSX. For example, you can't use statements like if or for directly within curly braces, as they are not valid expressions. In such cases, you can use conditional operators or map() to handle conditional rendering or iteration respectively.

Curious Case of Array.map

In JavaScript, the Array.map() function is invoked as array.map(callback) where callback is the function that will be called for each element in the array. The map() function applies the callback function to each element of the array and returns a new array with the results.

When using Array.map() in React JSX, it's important to understand that JSX requires a single expression to be returned, and Array.map() returns a new array. To handle this, parentheses ( ) are used to group and wrap the returned array from Array.map(), allowing it to be treated as a single expression.

Here's an example to illustrate the usage of parentheses with Array.map() in React JSX:

const numbers = [1, 2, 3, 4, 5];

return (
  <div>
    {numbers.map((number) => (
      <p key={number}>{number}</p>
    ))}
  </div>
);

In the above example, the numbers.map() function is called within the parentheses ( ), and the resulting array is directly embedded within the JSX expression. The callback function (number) => (<p key={number}>{number}</p>) returns a JSX <p> element for each number in the numbers array. The key prop is provided to ensure unique identification for each rendered element.

By wrapping the numbers.map() function in parentheses, it becomes a single expression that can be directly included within the JSX. This allows React to render the array of JSX elements returned by map() without any issues.

Without the parentheses, the JSX parser would interpret the curly braces { } of the map() callback function as a block of code instead of an expression. This would result in a syntax error in JSX.

To summarize, the parentheses ( ) are used when using Array.map() in React JSX to group the returned array from the map() function into a single expression that can be rendered within JSX.