JSX: The Beginning of React

Last updated on December 28, 2022

JSX is a syntax extension to Javascript but doesn’t it look like HTML? That’s the first question you will ask yourself when you see JSX code or any standard react template. It’s technically not HTML but to save you from the complexity you can say it is inspired by HTML. But, there is more to it. JSX basically allows you to write HTML syntax with javascript as an add-on. You can render values, and use javascript loops, pass events in JSX. Store this syntax in variables to be reused. Let’s look at the basics

Embedding Expressions

If you want a dynamic title for your blog post how would you do that in React? It’s simple

let name = "I am dynamic"
<h1>Title is: {name}</h1>

The above line of code will render the name variable into h1 and display it as h1 on the front end of the website. You can basically put any Javascript code in these curly braces. Write a mathematical expression called a function or whatever you desire.

Dynamic Attributes

With JSX you can define dynamic attributes for elements. Here is an example: the below code renders an image element whose src URL is fetched from DB. we can put a condition that after a certain amount of time the imageSrc is updated with a new URL from DB and the image on the frontend will change as well.

let imageSrc = "fetch some url from db based on a condition"
<img src={imageSrc} alt"I render an image based on a condition"/>

These are the two most important concepts of JSX more importantly JSX also prevents Injection Attacks. As it is impossible to insert something into JSX that is not explicitly written by you.

manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.