What is JSX and Components in React?

» What is a JSX in React?

  1. JSX stands for “JavaScript XML,” a syntax extension for JavaScript.

  2. In simpler terms, it’s a way to write HTML-like code within JavaScript files. It’s an integral part of React, and it’s used to describe what your user interface should look like.

  3. JSX has several features:

a. Familiar Syntax: It’s very similar to HTML, making it easy for developers like you and me to learn and use.

b. JSX is used to create React components, which are reusable building blocks for your user interface.

c. We can also embed JavaScript expressions within curly braces {} inside JSX. That will allow us to dynamically insert values.

» JSX example

  1. The example down is a React Component that is rendering a heading “Hello World”.

  2. But this code might look like HTML to us. But it isn’t. It’s actually JSX!

  3. This JSX code gets transformed into regular JavaScript code behind the scenes.

// App.js file
function App() {
  return (
      <div className="App">
        <h1>Hello World</h1>
      </div>
  )
}

export default App;

» Embeding JS expression in JSX.

  1. We use curly braces { } to insert JavaScript expressions.

  2. In App.js file: let’s create a variable called name and assign it a value of React and then insert a curly bracket in

    , and write our variable name that is name.

const name = "React";

function App() {
  return (
      <div className="App">
        <h1>Hello, {name}</h1>
      </div>
  )
}

export default App;
  1. In the above example, we’re dynamically inserting the value of the name variable that is React into our JSX.

  2. Save the file and this will refresh and here you will have a heading Hello, React.

» Self Closing Tags like break line and img

  1. Just like in HTML, we can use self-closing tags for elements that don’t have closing tags. For example:

  2. Create a paragraph below h1 and in between add a break line tag. Like this:

const name = "React";

function App() {
  return (
      <div className="App">
        <h1>Hello, {name}</h1>
        <p>
            Lorem ipsum dolor sit amet consectetur adipisicing elit.
            <br /> // break line tag.
            Quisquam, voluptatum. Quisquam, voluptatum. Quisquam, voluptatum.
        </p>
      </div>
  )
}

export default App;

» Style in JSX.

  1. We can apply inline styles to JSX elements using the style attribute

  2. However, the styles are to be defined as JavaScript objects with camelCased property names.

  3. For Example:

const style = {
    color: "blue",
     fontSize: "20px",
}
const name = "React";

function App() {
  return (
      <div className="App">
        <h1>Hello, {name}</h1>
        <h2 style={style}>React is awesome.</h2>
      </div>
  )
}

export default App;
  1. Here we create an object called style, which defines the color and font size.

  2. Inside the function,we create a

    tag with the style attribute, and to use this style object, embed style it as an expression inside {}.

» Class VS ClassName

  1. In JSX, use className instead of class for specifying CSS classes.

  2. This is because the class is a reserved keyword in JavaScript. So, that is why we use className instead of class.

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <h1>React App</h1>
      <img src={logo} className="App-logo" alt="logo" />
    </div>
  );
}

export default App;
  1. Above we are importing the react logo and also css.

  2. One thing you will notice is the className=“App-logo” attribute.

» Conditional Statements

  1. You can use ternary operators or conditional statements inside JSX to conditionally render elements.

  2. In React, there is no special syntax for writing conditions. We use the same syntax as JavaScript code. Let’s understand with an example:

function App() {
  const isLoggedIn = true; // You can change this to `false` to see the difference

  let heading;
  if (isLoggedIn) {
    heading = <h1>Welcome, User!</h1>;
  } else {
    heading = <h1>Please Log In</h1>;
  }

  return (
    <div>
      {heading}
    </div>
  );
}

export default App;
  1. Here we use the isLoggedIn variable to conditionally set the heading JSX element. If isLoggedIn is true, it displays a “Welcome, User!” heading; if it’s set to false, it displays a “Please Log In” heading.

  2. This demonstrates how you can use conditional statements to render different JSX elements based on the application’s state or logic.

  3. Instead of just using simple headings here, we can use components.

  4. Also, we can use the conditional operator instead of using if and else.

» JSX Fragments

  1. JSX normally requires a single-parent element.

  2. When we try to add another div, we will have errors: JSX expressions must have one parent element.

  3. To return multiple elements without adding unnecessary divs, you can use JSX fragments (introduced in React 16.2).

function App() {
  return (
    <> 
      <div className="App">
        <h1>Hello, React</h1>
      </div>
      <div>
        <h1>We using JSX fragments</h1>
      </div> // No ERROR because we are using JSX fragments.
    </>
  )
}

export default App;

» Components in REACT

  1. In React, a component is a reusable, self-contained piece of user interface that encapsulates a specific functionality or view.

  2. Components allow us to break down the application’s user interface into smaller, manageable parts.

  3. React has two types of components: functional components and class components.

  4. Functional components are JavaScript functions that will return JSX. These are simple and easier to read than class components.

  5. Class components are JavaScript classes that extend React.Component.

  6. The functional component does not store or handle the state, and that is why it is referred to as a stateless component. However, react provides a hook called useState() that enables function components to keep track of their state.

  7. Now it has been suggested to use Function components along with Hooks, which were added in React 16.8.

» Create a Component

  1. Whatever we did above, was basically a function component.

  2. Let’s create a folder named components in the source (src) directory and in that create the firstComponent.jsx file.

  3. Inside the file, start by importing react.

  4. Then create a function called FirstComponent and inside it let’s just return a heading Hello, FirstComponent which we are exporting also. Just like this:

// In firstComponent.jsx in src folder. 
import React from "react";

export default function FirstComponent() {
    return (
        <h1>Hello, First Component</h1>
    )
}
  1. In the App.js file, let’s import the first component JSX file; call our first component like this.
import FirstComponent from "./components/firstComponent";

export default function App() {
  return (
      <FirstComponent />
  );
}
  1. You can create as many components you want. Export them and import them in App.js file.

  2. You can also refer to react.dev documentation for this.

And That’s it! You’ve successfully learned about JSX and Components in REACT.

Thank You and Happy coding!😊