So here I will show you how to create use react without JSX. when you will go to any tutorial for the first time they will teach you about JSX first and then component and all the cool stuff.
But do you know that when react was created it was using plain JavaScript object to create components and all...
We will see that in this session:-
let's say you have a html file with a div tag like below
now you want to create few element and assign them to root, In plain js will do like this
const h1 = document.createElement("h1");
h1.innerHTML = "Hello world!";
const root = document.getElementById("root");
root.appendChild(h1);
And it will render it on browser perfectly fine.
Now coming to main topic how we will do the same for react using plain javascript
const h1 = React.createElement("h1",{},"Hello world");
const root = ReactDOM.createRoot("root");
root.render(h1);
hurrah we have create one react element using plain js
now if you want to add multiple element to root you can do it by simply doing this
const firstName = React.createElement("h2",{id:fName,"abc"};
const lastName = React.createElement("h2",{id:lName,"xyz"};
root.render([firstName,lastName]);
Top comments (1)
Could you please elaborate on what would be the practical use of that approach?
Here are a couple of points I would like to make about it:
This is the exact reason why React introduced
JSX
, otherwise it would not even make any sense to create the framework because we already had vanilla JavaScript…You are using
innerHTML
, which is bad practice, as it creates a security risk for the application.When React was first released, in order to create a component, you could do so as the following:
This approach was way back in the days - circa 2013. After that, class components came and nowadays we have functional components, which are so much better to work with than the latter.
In summary, using the vanilla JavaScript DOM approach would take you 10x longer to develop a larger scale app, not to mention the incredible mess it would be to maintain all of that code.