Explain it like I'm 5 - JSX
JSX is JavaScript XML, an XML-like extension for traditional JavaScript. Originally, it was developed by the folks over at Facebook for React, but it is used in many other frameworks now too.
Ok, what does this actually mean?
JSX lets you put HTML right into your JavaScript. That's really it! Pretty simple. For example, in vanilla JS, to create a div
containing three paragraphs with a custom class you would need to do something like this.
const createDivAndParagraphs = () => { const div = document.createElement('div'); div.classList.add('customClass'); const p1 = document.createElement('p'); p1.innerText = 'Paragraph 1'; const p2 = document.createElement('p'); p2.innerText = 'Paragraph 2'; const p3 = document.createElement('p'); p3.innerText = 'Paragraph 3'; div.appendChild(p1); div.appendChild(p2); div.appendChild(p3); }
11 lines of code and it's not very pretty to look at. You can imagine as this gets more complicated the code gets even harder to write, maintain, and read. This is where and why JSX comes in. What are we trying to create? Some HTML. So why don't we just write that. With JSX we can, like this:
const createDivAndParagraphs = () => { return( <div className="customClass"> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> </div> ); }
Half the lines, much easier to read, that is why we have JSX. Now we can have our markup in the same file as the code. It makes code easier to write and manage.
How does it work?
We have covered everything you really need to know about JSX up to this point. But it does beg the question, how does it work? JSX does not run natively in the browser, browsers are designed for JavaScript. So we need a transpiler to convert the code to traditional JavaScript. This is handled by libraries like React.
Enjoyed this article? Subscribe to the RSS Feed!