React.js: The Basics

React.js: The Basics

Hello there 👋

Today, I will be teaching you everything I know about the basics of React.js and how to use it in your react project.

Table of Contents

  • React.js

  • Introducing JSX

  • Rendering HTML

  • React Components

  • React Props

  • React State

Let's start learning 🚀

React.js

React is a JavaScript library for building user interfaces and it is used to build single-page applications. It allows us to create reusable UI components. It presents data that changes over time. Lots of people use React as the V in MVC ( Model-View-Control). React abstracts away the DOM (Document Object Model) from you, offering a simpler programming model and better performance.

Note: Most people mistake React as a Frontend (JavaScript) framework. It is a library.

Difference? JavaScript libraries are like pieces of furniture that add style and function to an already constructed house. Frameworks, on the other hand, are a template you use to build the house itself.

React.js code looks like this:

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

This is the smallest react code you will ever see 😅

Let's dissect the code :

ReactDOM : ReactDOM is a package that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient way of managing DOM elements of the web page. It works by exposing several top-level APIs to interact with the browser DOM.

What is a DOM?: The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents.

ReactDOM.render: ReactDOM. render() controls the contents of the container node you pass in. Any existing DOM elements inside are replaced when first called.

An example of a JSX code

const myelement = <h1>I Love JSX!</h1>;

ReactDOM.render(myelement, document.getElementById('root'));

This line of code returns Hello, world as a header 1.

document.getElementById('root'): The Document method getElementById() returns an Element object representing the element whose id property matches the specified string, root.

Introducing JSX

JSX stands for JavaScript XML. It is simply a syntax extension of JavaScript. It allows us to directly write HTML in React (within JavaScript code).

An example of JSX

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

This is a funny syntax. It has not a string or HTML. I recommend using it with React to describe what the UI( User Interface) should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

Why JSX?

I know, right? I am asking the same question.

React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.

Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. We will come back to components much later, but if you’re not yet comfortable putting markup in JS, this article might convince you otherwise.

React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI (User Interface) inside the JavaScript code. It also allows React to show more useful error and warning messages.

Coding JSX

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications.

Expressions & Attributes in JSX

JSX supports expressions inside curly braces { } i.e, you can write if statements and for loops, assign it to variables, accept it as arguments, and return it from functions.

const myelement = <h1>React is {5 + 5} times better with JSX</h1>;

JSX can hold a large block of HTML and one top element.

The HTML code must be wrapped in ONE top-level element. If you like to write two headers, you must put them inside a parent element, like a div element.

const myelement = (
  <div>
    <h1>I am a Header.</h1>
    <h1>I am a Header two.</h1>
  </div>
);

For attribute,

The class attribute can't be used because JSX is rendered as JavaScript, and the class keyword is a reserved word in JavaScript, use className instead.

JSX Prevents Injection Attacks

const title = response.potentiallyMaliciousInput;
// This is very safe:
const element = <h1>{title}</h1>;

By default, React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.

Rendering Elements

Elements are small building blocks of react app. Unlike DOM elements, React elements are plain objects and are cheap to create.

NOTE :

One might confuse elements with a more widely known concept of “components”. Elements are what components are “made of”.

Using The Render Function

Earlier, I spoke about .render(). Let's talk about how it helps react app. The purpose of the function is to display the specified HTML code inside the specified HTML element.

Updating the Rendered Element

In practice, most React apps only call ReactDOM.render() once. Once you create an element, you can’t change its children or attributes.

The only way I know how to update the UI is to create a new element and pass it to ReactDOM.render().

React Components

Components are like functions that help the HTML work. It helps split the UI into independent and reusable bits of code. It serves the same purpose as JavaScript functions, but work in isolation and return HTML via a render() function. There are two types; Class components and Function components.

Class components

The component has to include the extends React.Component statement, this statement creates an inheritance to React.Component, and gives your component access to React.Component's functions.

To write a class component, the component's name must start with an upper case letter. It requires .render() method and it returns HTML.

class Test extends React.Component {
  render() {
    return <h2>Hi,This is an example</h2>;
  }
}

Function components

A Function component also returns HTML and behaves pretty much the same way as a Class component.

function Test extends React.Component {
  render() {
    return <h2>Hi,This is an example</h2>;
  }
}

Note: Always start component names with a capital letter. React treats components starting with lowercase letters as DOM tags.

Component Constructor

A constructor() function in your component is called when a component is initiated. It is where you initiate the component's properties. The constructor function is also where you honor the inheritance of the parent component by including the super() statement, which executes the parent component's constructor function, and your component has access to all the functions of the parent component (React.Component).

class Book extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }
  render() {
    return <h2>I am a Novel!</h2>;
  }
}

React Props

Props are arguments passed into React components and passed to components via HTML attributes. Whether you declare a component as a function or a class, it must never modify its props.

They are like function arguments in JavaScript and attributes in HTML.

To send props into a component,

const myelement = <Car brand="Ford" />;

# The component receives the argument as a props object

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.brand}!</h2>;
  }
}

Note: React Props are read-only! You will get an error if you try to change their value.

React State

The state object stores property values that belong to the component. When the state object changes, the component re-renders.

The state object is initialized in the constructor:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {brand: "Ford"};
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

//The state object can contain as many properties as you like:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

Using the state Object

You can refer to the state object anywhere in the component by using the this.state.propertyname syntax

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
      </div>
    );
  }
}

Changing the state Object

You can change a value in the state object, use the this.setState() method.

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

Always use the setState() method to change the state object, it will ensure that the component knows it's been updated and calls the render() method (and all the other lifecycle methods).

Yay! 🎉 You are almost a react developer. Build projects as you learn, that would be very beneficial.

Was this article helpful? Let me know in the comment section.

Sources :

geeksforgeeks.org/jsx-full-form/#:~:text=JS...

w3schools.com/react/default.asp

reactjs.org/docs/hello-world.html

Keep in touch:

Thanks for reading till the end ❤️. You can contact me via Email and Discord:

Email -

Discord - Sophyia#8929