Jsx as Template

Jsx as Template

Aug 27, 2022
react

JSX as a templating language #

If you are doing web development in react, you would know what JSX is. If not go look it up, I’m not going to explain. And if your using typescript in web development it’s tsx.

This is how a sample JSX looks like

const SampleJsx = () => {
    return (
        <div>
            <div>SampleJSX<div>
        </div>
    )
}

And this is how a regular XML looks like

<parentSection>
    <childSection>This is a child content</childSection>
</parentSection>

If we remove the const, return and other language construct of javascript(or ecmaScript, if you like to call it that) this is how it would look

 <div>
    <div>SampleJSX<div>
</div>

But wait that’s not how a XML looks like, it always start with some wearied syntax that says what version it’s and some encoding right, something like this.

<?xml version="1.0" encoding="UTF-8"?>

That’s prolog, it’s very important for xml files to include that.

All these are fine, but how these relates to jsx being a template language, right.

You see, the xml files are static or in other words if we output from the xml file it’s output is same in most situation. And if we output the jsx file, even it’s same in most situation, but that’s not what we do. We use it with javascript.

You see jsx already uses HTML tags, it doesn’t want us to write any fancy element and define it later. Since it uses HTML it’s definition is taken care of. What we do is write custom elements, we combine the elements provided by HTML, use javascript to provide input to it and puff, we have a jsx element with different output.

Let’s take the jsx example we defined above, and change up few things. Instead of having hardcoded SampleJSX let’s take that through a prop and call it innerDiv and enclose this within the braces {}.

const SampleJsx = ({ innerDiv } : prop) => {
    return (
        <div>
            <div>{innerDiv}<div>
        </div>
    )
}

When I use this element elsewhere, I can pass in values to the SampleJsx element by changing the value of innerDiv id <SampleJsx innerDiv="SampleJSX" />

Know you would be thinking, “I already know all these things and I write better [J|T]SX or react component than you and wasted my 2-3 mins of my day reading your shit post in here.” Right, but there is more to jsx than this, but that’s for another notes. 👋 👋 🏃