ReactJS, JSX, Rendering Elements, React Components and Props

Syed Aquib AliSyed Aquib Ali
7 min read

What is React

React is a JavaScript library created by FaceBook (in 2013) and made it public in 2017. React was build for building user interfaces. React is used to build single page applications. React allows us to create re-usable UI components.

How does React work

React created a virtual DOM in memory. instead of manipulating the browser DOM directly, React creates a virtual DOM in memory, where it does all the necessary manipulating, before making the changes in the browser DOM.

Requirements

In order to start with React, first you will need to have nodeJS installed inside of your machine. The version of nodeJS should be above v14. If you have installed node then in your terminal you can simply write node -v and it should give response as:

node -v
v20.12.2

Creating React App

Now that everything is set, you can go to a directory in your terminal where you want to create your App and do:

npx create-next-app demo

It will take fair amount of time since the package size is 300mb's+. Once it is done do cd demo in your terminal to go to the folder we have just created and do npm start and it will run on localhost:3000 by default.

React behavior

Before React we always used to open our html file through live server extension but in React if we do that it will just show us a blank white screen and nothing else, as compared to npm start where we got a basic template from React.

Features of React

There are many built in features inside of React that solved many of our problems. Such as:

  1. Component-Based Architecture:

    • React encourages the building of reusable UI components. These components can manage their state and be composed together to build complex user interfaces.
  2. Virtual DOM:

    • React uses a Virtual DOM to optimize rendering. When the state of an object changes, React updates the Virtual DOM first, which is a lightweight copy of the actual DOM. It then compares the Virtual DOM with the actual DOM and updates only the parts of the DOM that have changed. This process is called reconciliation and makes updates more efficient.
  3. Declarative UI:

    • React allows developers to describe what the UI should look like for different states of the application. When the data changes, React efficiently updates and re-renders the appropriate components.
  4. JSX:

    • JSX is a syntax extension that looks similar to XML or HTML and is used with React to describe what the UI should look like. JSX allows writing HTML structures in the same file as JavaScript code, making the code more readable and easier to manage.
  5. Unidirectional Data Flow:

    • In React, data flows in one direction, from parent to child components. This unidirectional data flow makes it easier to understand how data changes affect the application.
  6. Hooks:

    • React introduced hooks (e.g., useState, useEffect) to allow state and other React features to be used in functional components, making them more powerful and versatile.
  7. Ecosystem and Tooling:

    • React has a rich ecosystem of tools, libraries, and extensions (such as Redux for state management, React Router for routing, and Next.js for server-side rendering) that enhance its functionality and development experience.

JSX

JSX (JavaScript XML) is an extension for JavaScript, often used with React, a popular JavaScript library for building user interfaces. JSX allows developers to write HTML-like code directly in their JavaScript files, making it easier to describe what the UI should look like.

const element = <h1>Hello, world!</h1>;
  • <h1>Hello, world!</h1> is JSX syntax.

  • const element = ... is a JavaScript variable declaration.

JS vs JSX
If we were inside the JavaScript and wanted to create an element we had to do const div = document.createElement("div"); then div.innerHTML = "Hello, world!";. But here we just wrote it like a normal HTML inside of our JavaScript.

If we want to add more than one h1 in one variable we will have to use a new syntax:

const element = (
    <div>
        <h1>Hello, world!</h1>
        <h2>This is another text.</h2>
    </div>
);

As you noticed I wrapped it inside a parenthesis and also wrapped my content inside a div. What react says is that multiple contents must be wrapped inside a parent to let it work.

  1. XML-Like Syntax: JSX syntax closely resembles XML/HTML, making it easy to write and read for developers familiar with web development.

  2. JavaScript Expressions: You can embed JavaScript expressions within curly braces {} in JSX. For example:

     const user = {
       firstName: "Aquib",
       lastName: "Ali"
     };
     const element = <h1>Hello, {user.firstName} {user.lastName}!</h1>;
    
  3. Attributes: JSX allows you to specify HTML attributes using the same syntax as HTML. For example:

     const element = <img src="path/to/image.jpg" alt="An image" />;
    
  4. JSX is an Expression:

    • JSX is an expression too, which means it can be used inside if statements and for loops, assigned to variables, accepted as arguments, and returned from functions.
function getGreeting(user) {
  if (user) {
    return <h1>Hello, {user.firstName} {user.lastName}!</h1>;
  }
  return <h1>Hello, Stranger.</h1>;
}
  1. Styling in JSX:

    • Inline styles in JSX are specified as an object.
const divStyle = {
  color: "blue",
  backgroundColor: "black"
};
const element = <div style={divStyle}>Styled div</div>;
  • If we were not using a variable for style and wanted to directly write it inside style tag, we will have to do it like:
const element = <div style={{color: "blue", backgroundColor: "black"}}>Styled div</div>;
  1. Conditional Rendering:

    • You can use JavaScript conditional statements to conditionally include elements in the JSX.
const isLoggedIn = true;
const element = (
  <div>
    {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
  </div>
);
  1. Lists and Keys:

    • Rendering a list of elements requires a unique key prop for each element to help React identify which items have changed.
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);
const element = <ul>{listItems}</ul>;

Understanding JSX Compilation:

JSX is not valid JavaScript by itself. Browsers cannot read it directly. Therefore, JSX code must be compiled into regular JavaScript using tools like Babel. For example, the JSX:

const element = <h1 className="greeting">Hello, world!</h1>;

is compiled to:

const element = React.createElement(
  "h1",
  { className: "greeting" },
  "Hello, world!"
);

React's createElement method creates an object representing the DOM node, which React uses to efficiently update the DOM to match the element's description.


Rendering Elements

React involves creating and displaying React elements in the DOM. React elements are the smallest building blocks of React applications and are essentially JavaScript objects that describe what you want to see on the screen.

Rendering a React Element to the DOM:

  1. Creating an Element:

    • A React element can be created using JSX or by calling React.createElement.
// Using JSX
const element = <h1>Hello, world!</h1>;

// Using React.createElement
const element = React.createElement("h1", null, "Hello, world!");
  1. Rendering the Element:

    • To render a React element into the DOM, you use the ReactDOM.render method. This method takes two arguments: the React element to render and the DOM element to render into.
// Assuming there is a div with id 'root' in your HTML
const rootElement = document.getElementById("root");
ReactDOM.render(element, rootElement);

Updating the Rendered Element:

React elements are immutable. Once you create an element, you cannot change its children or attributes. To update the UI, you need to create a new element and render it again.

// Initial render
const element = <h1>Hello, world!</h1>;
ReactDOM.render(element, rootElement);

// Updating the render
const updatedElement = <h1>Hello, React!</h1>;
ReactDOM.render(updatedElement, rootElement);

Rendering Components and Props

Components are reusable pieces of UI. You can define a component and render it just like you would with any other React element.

  1. Functional Components:
             // Receiving the value as a prop
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// Rendering the component
                      // Passing down to the props
const element = <Welcome name="Aquib" />;
ReactDOM.render(element, rootElement);
  1. Class Components:
class Welcome extends React.Component {
  render() {
                   // Directly using the value using this keyword
    return <h1>Hello, {this.props.name}</h1>;
  }
}

// Rendering the component
                      // Passing down to the props
const element = <Welcome name="Aquib" />;
ReactDOM.render(element, rootElement);

Rendering Multiple Elements:

If you want to render multiple elements, you can wrap them in a parent element, such as a div, or use a React Fragment (<> and </>).

const element = (
  <div>
    <h1>Hello, world!</h1>
    <h2>Good to see you here.</h2>
  </div>
);

ReactDOM.render(element, rootElement);

Or using a Fragment:

const element = (
  <>
    <h1>Hello, world!</h1>
    <h2>Good to see you here.</h2>
  </>
);

ReactDOM.render(element, rootElement);

Using a fragment is more recommended because you would not want to have unnecessary amount of div's.

  • React Elements: Basic building blocks, immutable, created using JSX or React.createElement.

  • ReactDOM.render: Renders React elements or components into the DOM.

  • Components: Reusable pieces of UI, can be functional or class-based.

These principles are fundamental to working with React and form the basis for creating dynamic, interactive web applications.

0
Subscribe to my newsletter

Read articles from Syed Aquib Ali directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Syed Aquib Ali
Syed Aquib Ali

I am a MERN stack developer who has learnt everything yet trying to polish his skills 🥂, I love backend more than frontend.