When React was first introduced, one of the features that caught most people’s attention (and drew the most criticism) was JSX. If you’re learning React, or have ever seen any code examples, you probably did a double-take at the syntax. What is this strange amalgamation of HTML and JavaScript? Is this even real code?
Let’s take a look at what JSX actually is, how it works, and why the heck we’d want to be mixing HTML and JS in the first place!
What is JSX?
Defined by the React Docs as an “extension to JavaScript” or “syntax sugar for calling React.createElement(component, props, ...children))
”, JSX is what makes writing your React Components easy.
JSX is considered a domain-specific language (DSL), which can look very similar to a template language, such as Mustache, Thymeleaf, Razor, Twig, or others.
It doesn’t render out to HTML directly, but instead renders to React Classes that are consumed by the Virtual DOM. Eventually, through the mysterious magic of the Virtual DOM, it will make its way to the page and be rendered out to HTML.
How Does it Work?
JSX is basically still just JavaScript with some extra functionality. With JSX, you can write code that looks very similar to HTML or XML, but you have the power of seamlessly mixing JavaScript methods and variables into your code. JSX is interpreted by a transpiler, such as Babel, and rendered to JavaScript code that the UI Framework (React, in this case) can understand.
Don’t like JSX? That’s cool. It’s technically not required, and the React Docs actually include a section on using “React Without JSX”. Let me warn you right now, though, it’s not pretty. Don’t believe me? Take a look.
JSX:
class SitePoint extends Component {
render() {
return (
<div>My name is <span>{this.props.myName}</span></div>
)
}
}
React Sans JSX:
class SitePoint extends Component {
render() {
return React.createElement(
"div",
null,
"My name is",
React.createElement(
"span",
null,
this.props.myName
)
)
}
}
Sure, looking at those small example pieces of code on that page you might be thinking, “Oh, that’s not so bad, I could do that.” But could you imagine writing an entire application like that?
The example is just two simple nested HTML elements, nothing fancy. Basically, just a nested Hello World
. Trying to write your React application without JSX would be extremely time consuming and, if you’re like most of us other developers out here working as characters in DevLand™, it will very likely quickly turn into a convoluted spaghetti code mess. Yuck!
Using frameworks and libraries and things like that are meant to make our lives easier, not harder. I’m sure we’ve all seen the overuse and abuse of libraries or frameworks in our careers, but using JSX with your React is definitely not one of those cases.
Continue reading An Introduction to JSX on SitePoint.
No comments:
Post a Comment