Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 13, 2023 04:26 pm GMT

React API for JavaScript Devs

React is a widely-used JavaScript library for building modern and visually appealing user interfaces. It provides the capability for developers to create reusable components, which can be combined to create complex UIs.

Before delving further into React, it's assumed that you have a basic understanding of how React components are written using JSX, a syntax extension for JavaScript that allows for easy creation of markup. If you need to learn how to write markup using JSX, you can refer to this link.

React and DOM (Document Object Model)

React makes use of virtual DOM (Document Object Model) to update and maintain the state of user interface. It updates the actual browser DOM as needed.

The DOM represents the structure of a web page in the form of a tree of nodes, where each node represents an HTML element, an attribute, or a text node. Whenever a web page changes, the DOM needs to be updated to reflect the changes. You can see the real time dom visualization here.

Here are some common and most important DOM methods you should know to understand React API.

createElement

This method, as its name says is used for creating HTML elements.

Syntax - document.createElement(tagName, options)

Parameters -

  • tagName (string) : name of HTML element (h1, p, img)
  • options (object) : optional

Example -

const root = document.createElement('div')

The above example will create a div element and store it inside the root variable.

Learn more about createElement here.

Writing text to a node

In the above example of createElement, we created a plain empty HTML div. Now let's learn how to write a text to HTML element.

Let us start by creating a new paragraph tag.

const greeter = document.createElement('p')

Now we have a paragraph tag created and stored inside greeter variable. Now to add a text content to this element, there are two ways.

  1. Creating a text node
const textNode = document.createTextNode('Hello World')

Using this approach, you will have to create a text node and then append it to the greeter/paragraph element.

greeter.appendChild(textNode)

This in result will look like <p>Hello World</p>.

  1. Using textContent property
greeter.textContent = 'Hello World'

This in result will look like <p>Hello World</p>.

Appending to existing element

An HTML page is a collection of different elements that make up the user interface. It can also contain nested elements such as,

<div id="hero">  <p>Hello World</p></div>

To create the above structure, we need to understand append and appendChild methods of DOM.

These methods are used for appending a text or a new element to the existing element.

Example -

// Creating a divconst root = document.createElement('div')root.setAttribute('id','hero')// Creating a paragraph elementconst greeter = document.createElement('p')greeter.textContent = 'Hello World'// Append greeter to rootroot.append(greeter)

The above example will generate the following structure -

<div id="hero">  <p>Hello World</p></div>

The append and appendChild methods work same. The key difference is that append method accpets string and nodes as parameters whereas appendChild method accepts only node elements. The appendChild method does not accept plain string as a parameter.

root.appendChild('Hello World') // this won't workroot.appendChild(document.createTextNode('Hello World')) // will work

Another difference is that the appendChild method returns the appended node object whereas append method does not return anything.

Last but not least,

Setting attributes

An attribute is a way to configure the HTML elements. These are some additional values that can be used to modify the behaviour of an element.

Examples - class, id, src, style

These are some commonly used HTML attributes. You can find detailed list of attributes here.

DOM provides setAttribute method to set attributes of an HTML element.

Syntax - element.setAttribute(name, value)

Parameters -

  1. name (string) : It is the name of attribute such as class, id etc.
  2. value (string) : A string containing the value of an attribute.

Example -

const root = document.createElement('div')root.setAttribute('id', 'root')

The above example will create a div element with id as root.

<div id="root"></div>

React

React uses following two core packages:

  • React:It is an entry point to the React library. It provides different methods for creating components, elements, refs, fragments, hooks, and many other things. It is a top level API of React.
  • ReactDOM:ReactDOM package provides DOM-specific methods. It provides methods like render, createPortal etc.

In this article, we will look into following three methods of React API.

  1. createElement
  2. createRoot
  3. render

createElement

The createElement function is a part of React library. Usually when writing React components we use JSX which makes it really easy to write components. The createElement function is not directly used if you are using JSX. If you were not using JSX to write components then there is a high chance that you would be using this function very frequently.

The JSX is just a syntactic sugar for calling createElement function.

Let's understand what this function does.

The createElement function lets you create a React element without writing JSX.

Syntax - createElement(type, props, ...children)

You can also pass children as a part of props then the syntax would become,

Syntax - createElement(type, props)

where props = {...props, children:[...children]}

Parameters -

  1. type - The type argument could be a tag name (string) such as div or span, or it could be a function, a class, or a fragment.
  2. props - The props argument must be a object or null. If you pass null then it is treated as an empty object.
  3. children - It can be zero or more child nodes.

Let's see how JSX component looks like when written using raw API syntax.

Here is a simple JSX Greeter component.

const Greeter = ({name}) => { return <div className="container">  <p>Hello {name}</p> </div>}

Here's how above JSX would look like when written using raw APIs.

const elementType = 'div'const elementProps = {className: "container"}const Greeter = createElement(elementType, elementProps, createElement('p', null, 'Hello', name))

You can use this link to see how JSX is transpiled in React.

As you can see, the component created using createElement is similar to JSX version but it is difficult to read and write. Hence, JSX is preferred to write components using React.

Learn more about createElement API here.

If you are interested in seeing the code for implementation of createElement in React official repo, click here.

createRoot

This function lets you create a root element to display React app inside a DOM node. It creates a React root from the given DOM node.

The beauty of React is that it can be used to build an entire application or only some part of the application.

If you are building entire application then you will have only single root node in your DOM tree. If you are using React to build only some part of the application then you can create a separate root for different components. You can use each root element to manage a different piece of UI.

Syntax - createRoot(domNode, options)

Parameters -

  1. domNode - A DOM element. The provided DOM element will be used for creating a root where app will be rendered. This root element then can be used to call functions like render to display the app content.
  2. options - An optional configuration object.

After a root is created, you have to call root.render(<App/>) to display a React component in it.

render

Render is a method used to display a JSX into React's root DOM node.

Syntax - root.render(component)

Parameters -

  1. It takes a React node as a parameter that you want to display. It can also take a string, number, null, or undefined as a parameter.

TL;DR

React is a popular JavaScript library that is used for building component driven user interfaces. In this article, we looked at different methods provided by React API such as createElement, createRoot, and render.


Original Link: https://dev.to/vivekalhat/react-api-for-javascript-devs-8d4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To