I’m learning React and I keep on hearing the phrase JSX.
I’ve tried watching videos about it but I still don’t understand what it is.
I’ve also had a look at the documentation but my head is still scrambled I’ve had a look at JSX and to me it just looks like regular HTML.
What is JSX and what is the difference between JSX and HTML?
4
Answers
JSX is what react uses to render content to page. JSX stands for JavaScript as XML, hence it’s HTML like syntax. The extra features of JSX that don’t come with just plain HTML is things like conditional rendering and dynamic content an example of each.
{showContent ? <p>This is content</p> : null}
<p>{counter} </p>
JSX is an extension to javascript syntax. It allows writing code that look similar html, and that similarity makes it feel pretty natural in the context of a front end UI library. JSX is very commonly used with React, though technically you could do react without JSX (it would be combersome, so i don’t recommend it), and the JSX syntax can be used with other libraries than react (this isn’t common).
In the context of react, a JSX element is a shorthand for calling
React.createElement
.createElement
is the code that React uses for describing what should be on the page. For example, the following JSX:Transpiles to this code:
Which will return an object that looks roughly like this:
That object is then used by React to decide what to do next to update the page to match your intention.
I know my answer is not so tecnical but basically JSX (or TSX if you’re using typescript) is the extension of visual (components) files of your react app. If you try to return any visual component in a JS/TS file you’ll get a lot of syntax errors.
And inside it you can now return the visual part of your app:
JSX basically allows us to write HTML in React as given below:
It’s called
JavaScript XML
which is basically a syntax extension for javascript, and in simple words it allows you to write javascript and HTML in a single file together.While JSX looks like HTML, but it’s not HTML. It gets converted (transpiled) into regular JavaScript by tools like Babel before being used in the browser.