React & JSX

404-Not-Found
2 min readOct 22, 2020

Before I thought React was just written a specific way and was used to it but I didn’t realize that React can written very differently compared to the usage of JSX.

JSX is a Javascript Extension and allows to write React in a way that looks like Javascript and HTML had a baby together and produced a hybrid syntax.

Let’s take a look at an example of how we would create an element using just React

React.createElement('h1', {className=page_title}, 'My Cool Title'),
React.createElement('p', {}, 'A Paragraph below the title'),
React.createElement('ul', {className=skills_list}, [
React.createElement('li', {}, 'Sleeping')
React.createElement('li', {}, 'Eating')
React.createElement('li', {}, 'Gaming')
])

Things start to get a bit crazy when you are starting to make complex pages and how things should be presented. Now, let’s look at it if we were to use JSX syntax instead.

<h1 className=page_title>My Cool Title</h1>
<p>A Paragraph below the title</p>
<ul>
<li>Sleeping</li>
<li>Eating</li>
<li>Gaming</li>
</ul>

Ok, now that you’ve seen the two, you might be asking, why would I ever want to write more and not less? Good question, so I did some digging.

Apparently, you would want to use the first method if, and I quote the React article, “…you don’t want to set up compilation in your build environment”.

What does that even mean??? I had no idea, so I had to google some more and came across a few resources.

First thing you need to know is if you did want to just open up your Editor and type in JSX into your .js file and tried to render it and look at it on your page, it wont work. It’s because web browsers won’t understand it. Therefore, before it reaches the web browser it needs to be complied and translated to good ‘ol Javascript.

How does it do this? Well, magic. Just kidding, you have to set it up correctly in your project by using Babel, which is tool that complies your code to the latest Javascript or some supported version of Javascript based on the features.

Now, when you try to render your components it will work since the web browser can understand it!

But here’s the catch! You can use create-react-appand it will do all of the nitty gritty set up for you, so really there’s no reason to have to use the first option if your problem to setting up a compilation since there’s something that will do it for you. The only other I found why people would use the first reason is they are lazy or don’t want to learn JSX syntax, but in my opinion that learning the syntax allows me to be lazier since I have to write less.

--

--

404-Not-Found
0 Followers

I enjoy long naps on the couch, deep conversations about video games, and romantic dinners with anime.