Getting Started With Pure React

Getting Started With Pure React

A lot of you might be already aware of how to use react or might be still struggling with where to start. In both cases, this blog might be worth a read for you. Why? Because if you already know React then you might have asked a question about yourself how magically JSX handles everything around creating new elements for us. And if you know nothing about React then you might want to start from a point where you can learn about absolute basic functions of function without any added sugar of the capabilities that other libraries provide.

So, how exactly React creates multiple HTML elements and how can you use the capabilities of React to create new HTML elements using JS? So, if we go to absolute basics then React provides some simple functions using which you can create React elements.

What is react element?

An element is a lightweight description of a piece of the user interface.

A react element is a simple object describing what properties an actual DOM node should be having. When you create a react element then it doesn't automatically get rendered. You later need to manually make an extra effort to render these react elements on the DOM.

React elements are just a simple way to represent the HTML elements to be rendered as plain objects.

{
  type: 'button',
  props: {
    className: 'btn btn-primary',
    children: 'Submit'
  }
}

The above JSON represents how a React element will look like, which React will later render in the DOM.

<button class='btn btn-primary'>
  Submit
</button>

The above HTML represents what type of HTML element our JSON is going to create once React picks these elements and add them to the DOM.

So, in react you can create these elements using createElement API or using JSX. JSX is nowadays the go-to way to create these elements. But in this blog, we will try to understand the legacy createElement API how you can use it to create react elements.

Why you should learn about createElement?

If you go to the official docs of JSX then the first line that is mentioned there is:

Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, ...children) function.

So technically, the internals of JSX is already using createElement. So, as a developer, you should not feel JSX to be some black box that magically creates a new React element.

More about createElement

The createElement function takes 2 main arguments i.e. type and props and one optional argument i.e. children.

  • type: The type argument tells the function about what element is expected to be created may be a button or a div or a span or maybe another React component.

  • props: Props argument is an object that contains a set of key-value pair-defining props for your React element. What are props? Props are additional properties or attributes that you can pass to your react elements. You can relate this with normal attributes that you pass with HTML elements like id or class but in the world of React these attributes can have a different label for example: class in HTML is replaced by className in React props. We can discuss more props in a separate blog, but for now, your takeaway about reacts props should be that these are additional properties of a react element. The props object can be empty also as it is not mandatory to have a prop and if we pass this props property as null then it will behave in the same way it would have behaved if we passed an empty object to it.

  • ...children: This is an optional argument. This argument defines zero or more child nodes that you can add to the react element's (which we want to create) DOM node. The child nodes are expected to be valid react elements, strings, numbers etc.

So, now we know a brief about the details of the createElement function, but let's take a deep dive and see this function in action as a basic HTML file.

Let's start writing some code:

Let's make a simple HTML file in your favourite text editor:

<!DOCTYPE html> <!-- index.html -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

</body>
</html>

let's add a bunch of script tags to bring React and ReactDOM into our HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <script src="https://unpkg.com/react@18.2.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script>
</body>
</html>

In the above piece of code, we have added two script tags to mainly download the JS code React and ReactDom library. Now you might be wondering what are these libraries required for.

Let's understand a brief meaning of both React and ReactDOM specifically. So React is a library shared among other libraries like ReactDOM, React Native etc. The react library contains the source code creation and handling for components, state, props and all the code that is React.

Having said that let's use our createElement function to create a new react element.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <script src="https://unpkg.com/react@18.2.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script>
    <script>
        // Creating new React Element
        const App = () => {
            return React.createElement(
                "div",
                {},
                React.createElement("h1", {}, "Welcome Welcome")
            );
        }
    </script>
</body>
</html>

The above createElement the function tries to create a new div with no props and having one child element as an h1 tag (h1 tag has a child which is just a normal string).

But if you will refresh your page you will get nothing on the webpage !!!

But why?

Because as we mentioned earlier that this function only creates a new React element, which is just a plain object, but it doesn't add it to the DOM. We have to make a manual effort to attach it to the DOM.

For that, we first need to select an element from our HTML which can act as the Root element of our DOM tree. Whatever new elements we are creating using createElement will be attached as a child of this Root node.

We will create an empty div with an id as root (you can keep any id) and then using our ReactDOM library create this div the Root of the Dom tree and then render our new React element inside this. We can use the ReactDOM.createRoot() to create a new root and render the function of this root to render a new React element.

In earlier React version, we used to achieve the same thing using ReactDOM.render() method but using the new ReactDOM.createRoot() method signals React, that you want to trigger the latest Version 18. Also, this provides you with manual access to the render method, which you can trigger anytime if you want to re-render everything in the whole app. Read more about createRoot here.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@18.2.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script>
    <script>
        const App = () => {
            return React.createElement(
                "div",
                {},
                React.createElement("h1", {}, "Welcome Welcome")
            );
        }
        // selecting the root element from the html
        const rootContainer = document.getElementById("root");
        // creating the root node of the DOM
        const root = ReactDOM.createRoot(rootContainer);
        // rendering the new element in the root by calling
        // App function
        root.render(App());
    </script>
</body>
</html>

You will get an output like this:

You can call render more than once on the same root. As long as the component tree structure matches up with what was previously rendered, React will preserve the state. Read more on this here

And boom 🔥 you have created your first React element without using any JSX code.

This can be a great starting point if you have been struggling to understand the internals of JSX or if you're an absolute beginner in ReactJS.

Do drop your suggestions in the comments below.

.

.

.

.

Lukewarm regards

Sanket Singh