In the journey of learning react,it is important to remember the fundamentals of web development at all times. One such fundamental aspect is understanding how elements are generated or created ? We can create elements with plain HTML, Javscript and React.
1. Through plain HTML
We simply create heading element using h1 tag and div tag having id=root and run the code, it will show "Hello from HTML!" on your webpage.
<body>
<div id="root">
<h1 id="heading">Hello from HTML!</h1>
</div>
</body>
2. Through plain Javascript
We first create a root element. Now to create heading element, we will use doucment.createElement and will provide the content through .innerHTML. Now, this new created heading is served to root using root.appendChild. Now when we run the code, it will show "Hello from Javscript!" on your webpage.
<body>
<div id="root">
</div>
<script>
const heading=document.createElement("h1");
heading.innerHTML="Hello from Javscript!"
const root=document.getElementById("root");
root.appendChild(heading);
</script>
</body>
3. Through plain React
We can create heading element in React using React API. We can inject React into our code by adding cdn links.
<body>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js">
</script>
</body>
This will provide us React and ReactDOM api.
Now we can create heading element using React.createElement and will serve this heading to root element using root.render method.
On running the code, it will show "Hello from React!".
<script>
const heading= React.createElement("h1",{},"Hello from React")
const root=ReactDOM.createRoot(document.getElementById("root"))
root.render(heading)
</script>
In conclusion, understanding how to create elements using HTML, JavaScript, and React is a fundamental aspect of web development. By mastering these techniques, you can build beautiful and functional web pages and applications. So whether you're just starting out or looking to expand your skills, keep these methods in mind and happy coding!
Top comments (0)