Doing things without React
Everyone who has been working with REACT has come across a situation where he needs to render the same component for so many items. For example,
import Card from "./Components/Cards"
export default function App() {
const arr = [1,2,3,4,5,6]
return (
<div className="App">
<>
{
arr.map((ele,idx) => {
return <Card key={idx} count={ele}/>
})
}
</>
</div>
);
}
And Card is a simple react component, which looks like this:
import React from "react"
const Card = ({count}) => {
return (
<>
<div>
<p> I am a card {count} </p>
</div>
</>
)
}
export default Card
And the output for this looks something like this:
We all have done this so many times, that it is hard to think of any other way of doing this. And if I ask you to do the same without React i.e using only HTML and JS? So let's try to do this.
Setting up HTML:
<!DOCTYPE html>
<html>
<head>
<title> Hello World! </title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<div id="card">
</div>
<script src="src/index.js">
</script>
</body>
</html>
We have created a div with id="card" which will show all the cards.
And index.js:
const arr = [
1,2,3,4,5,6
]
let cardBox = document.getElementById("card")
const showCards = () => {
for(let i=0;i<arr.length;i++) {
let para = document.createElement("p")
para.innerHTML = `I am a Card ${arr[i]}`
cardBox.appendChild(para)
}
}
showCards()
Let's go line by line, Firstly we are defining an array "arr", which is a dummy content which we will be rendering. We then target the div with id="card" and assign it to a variable cardBox. After that, we define a function "showCards()" responsible for rendering all the data of our dummy array on the window. Inside it, we create a new "p" tag and change its content to our desired text. We then add this to our cardBox.
At last, we are calling this showCards function.
If we look at the output,
So we got the same output as before (please ignore the font and alignment, :-( ). But this time, it was not that straightforward.