Using JSX

Ronan McClorey
2 min readJan 17, 2021

--

What is JSX? It is a syntax extension to JavaScript. It is often used when writing code with React to produce React “elements”. Written out it looks similar to HTML (because of the tags) but it has the full power of JavaScript. While going through Flatiron Bootcamp learning React we learned about JSX.

Photo by Dominik Malinowski on Unsplash

If the JSX is a DOM element it gets displayed on the DOM as written. Inside JSX we can also call other components it reads the components and displays them on the screen. This is done with the help of Babel so the code we are writing in React can be done without JSX but it makes the code a lot clearer using JSX and Babel converts the code to be read by the web browser(You get babel on your app automatically if you use create-react-app). Here’s a simple example using JSX vs not. Without JSX we would have to use a function like this to create a simple div element:

React.createElement(“div”, null, “Hello”)

Whereas with JSX it’s as simple as:

<div>Hello</div>

And while in the above example it doesn't seem like a big deal it’s rare to be writing this little code for a real app and as the code gets longer the code without JSX only gets even longer and more complicated to understand.

While writing JSX for most of the code you want to write as HTML elements you can simply write them as you would in HTML. But, there are some exceptions first if you want to add a class to any element instead of class= “new” you would write className= “new”. Another difference is for inline styling in HTML an example would be:

<h1 style="background-color: green; color: red;">Hello</h1>

in JSX this would be:

<h1 style={{ backgroundColor: 'green', color: 'red'}}>Hello</h1>

We change it to be like a JavaScript object the “” are replaced with {{}}, styling like background-color lose the hyphen and become camelCased, and the values of the styling become strings.

Any JavaScript we want to write in our JSX we need to surround it with {} so it gets read as JavaScript. We are able to write JavaScript functions, call functions, or JavaScript variables. Below is an example of React code and JSX

The JSX is read and displayed as three h1 headers saying Hello.

--

--

No responses yet