Friday, November 18, 2022

JSX in React

If you have started working on React you would have definitely heard about JSX. In this tutorial we'll learn what is JSX, how to use JSX and what are the rules about using JSX.


What is JSX

JSX is a syntax extension for JavaScript that lets you write HTML-like markup with in a JavaScript file. In React you can write code as given below which is a mix of both JS and HTML.

function helloWorld(){
  return <h2>HelloWorld from React</h2>
}

As per React documentation the React philosophy is not to separate technologies by putting markup and logic in separate files but to separate concerns by creating Components that contain both markup and logic in a single file.

Since JSX is not valid JavaScript so browsers can't read it directly. It has to be translated (using transpiler like Babel) into React.createElement() calls.

The function helloWorld as written above would be transpiled behind the scenes into following code.

function helloWorld() {
  return React.createElement("h2", null, "Hello World from React");
}

Actually, React doesn't require using JSX but writing your code as a series of React.createElement() functions would be quite tedious. JSX is more intuitive as you have both UI and JavaScript code at the same place. It also allows React to show more useful error and warning messages.

Rules of using JSX

  1. At the end it is all JavaScript and in JavaScript a function can return a single value so that applies to JSX too. You can only return a single root element from a component. To return multiple elements from a component, wrap them with a single parent tag.

    Below JSX code will give an error as you are trying to return multiple elements.

    function Hello() {
      return(
        <h2>Hello World from React</h2>
        <p>This is the React code</p>
      );
    }
    

    Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

    You can use <div> to wrap multiple elements.

    function Hello() {
        return(
        <div>
            <h2>Hello World from React</h2>
            <p>This is the React code</p>
        </div>
        );
    }
    

    If you don’t want to add an extra <div> to your markup, you can write <> and </> which is a shorter syntax for declaring fragments.

    function Hello() {
        return(
        <>
            <h2>Hello World from React</h2>
            <p>This is the React code</p>
        </>
        );
    }
    

    Or you can explicitly use React.Fragment which has to be imported.

    import { Fragment } from "react";
    
    export default function Hello() {
        return(
        <Fragment>
            <h2>Hello World from React</h2>
            <p>This is the React code</p>
        </Fragment>
        );
    }
    
  2. JSX requires all the tags to be explicitly closed. Even the line break tag (<br>) and horizontal rule tag (<hr>) must be closed <br />, <hr /> otherwise you will get an error.

    Parsing error: Unterminated JSX contents.

  3. User defined React component must be capitalized. An element with a lowercase letter is considered to be a built-in component like <h2> or <div> and results in a string 'h2' or 'div' passed to React.createElement. When the component name is capitalized like <Hello /> that compiles to React.createElement(Hello) and correspond to a component defined or imported in your JavaScript file. For example if you have a Hello.js file which is then used in App.js

    Hello.js

    export default function Hello() {
        return(
        <div>
            <h2>Hello World from React</h2>
            <p>This is the React code</p>
        </div>
        );
    }
    

    App.js

    import Hello from "./Components/Examples/HelloWorld";
    function App() {
      return (
        <Hello />
      );
    }
    export default App;
    
  4. Most of the JSX attributes are in camelCase. JSX is translated into JavaScript and attributes written in JSX become keys of JavaScript objects, as showed in the React.createElement() code used above. But JS has limitations in valid variable names where you can't use dash or a reserved word like class.

    Since class is a reserved word, in React you write className.

    <div className="Test">
    

Including JavaScript expressions in JSX

When you want to pass String attributes to JSX you will enclose those attributes in single quote or double quotes.

<div className="Test">

If you want to include JavaScript expressions in JSX you need to wrap them in curly braces. That helps in making your code dynamic.

export default function Hello() {
    const name = 'Robert';
    return(
    <div>
        <h2>Hello World from {name}</h2>
    </div>
    );
}

In the example you first declare a constant name and then embed it with curly braces inside the <h2> tag.

You can even embed a JS function call between curly braces.

export default function Hello() {
    const curDate = new Date();
    // JS function
    const formatDate = (date) => {
        return new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long' }).format(date);
    }
    // rendering logic
    return(
    <div>
        <h2>Hello World, current date and time is {formatDate(curDate)}</h2>
    </div>
    );
}

That's all for this topic JSX in React. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Creating a New React Project - create-react-app
  2. React create-react-app Project Structure
  3. React HelloWorld App - First React App
  4. Access Modifiers in Java

You may also like-

  1. Angular Project Structure With File Description
  2. Lambda expressions in Java 8
  3. How HashMap internally works in Java

No comments:

Post a Comment