JSX — React (What, Why, and How)
While using React, you definitely would have come across JSX. In this article, we will understand What JSX is? Why is it being used? And How it works?
What is JSX?
JSX ( JavaScript Syntax Extension or JavaScript XML). It allows us to write JavaScript along with HTML. We can easily create React templates using JSX. Its syntax might look similar to templating languages like EJS, but it has all the functionality of JavaScript.
Here’s a simple example of How JSX looks like.
It might seem odd to use JS and HTML altogether but it can be pretty useful.
Why JSX?
In React logic rendering is totally linked to other user interface logic like changing of state, handling of various events, and displaying data. Instead of putting functionality and markup in separate files, React uses components which incorporates both markup and functionality. Of course React Components can be written without JSX, but with JSX it is so much easier. In order to understand it here is a typical example of how code will look with and without JSX.
How JSX works?
As JSX is not a valid JavaScript, it cannot be read by the browsers. Browsers don’t understand JSX, So here comes the need of transpilers like Babel or TypeScript that translates JSX syntax into JavaScript such that it becomes browser readable. It occurs internally during the building phase, browser will never know anything about JSX as browser will receive it after conversion done by react and babel. Let’s see how its converted with the help of an example.
Conclusion
In this article, we have understood what exactly is JSX, how it is a nice way to write plain old JavaScript objects, How its being used internally, also how it has made our lives easier. Hope this article helps.