JSX Walkthrough in React JS

JSX Walkthrough in ReactJS: If you’ve started studying React already, you should have heard a lot about JSX. You’ve also probably heard that it is not necessary to use it with React. And that much is true. But, it is recommended that you do. It just makes things so much easier, even though its syntax can appear a little scary at first to traditional JavaScript developers.

JSX is known for being a language that lets you “write HTML inside JavaScript.” This is true to some degree. The desired effect is that we can treat HTML tags as a JavaScript statement. However, JSX actually uses a form of XML which only resembles HTML, because it uses tag names that match those of standard HTML tags, such as DIV, UL, TABLE and so on.

Remember that even HTML is just a distant brother of XML. Although HTML as a JavaScript statement might look a bit dinosaurs at first, once you grasp the idea and get used to it, it really becomes second nature. It’s definitely something completely new and not usually done (and not even compile in most browsers today) but let’s take a look at what it actually looks like:

JSX Walkthrough Example

var scoreBoard = { Player 1: 10, Player 2: 25 };
<div className = "class 1" />;
<SomeCounter count {3 + 5} />
<ScoreBoardUnit data-index = "2">
<h1>Score Leaderboard</h1>
<Scoreboard className = "results" scores ={scoreBoard} />
</ScoreBoard Unit;

This code naturally will not compile in your standard browser unless Babel’s JSX plugin is helping us transpile it back into ES5, the specification we can be sure all modern browsers do understand. In this case, it will compile into following React elements.

React JS Example

var scoreboard = { Player 1: 10, Player2: 25 };
React.createElement('div', {className: 'class1'},null)
React.createElement( SomeCounter, count: 3 + 5),null)
React.createElement( ScoreBoard Unit, { 'data index': 2 },
React.createElement('h1', 0, 'Scoreboard),
React.createElement( Scoreboard, {
className: 'result',
Scores: scoreBoard), null)
// close React.createElement(ScoreBoard Unit...

These JSX and React code examples can be used synonymously. As long as you have JSX transpiring your code in the background, it will work and you can interchange between the two.

And while JSX is highly recommended for combining with React it is not necessary for using with or compiling React programs. Just use createElement syntax without JSX, if you must.

Once your files are actively transpired into ES5, you can begin using JSX in your own programs. As you can see from the example above, this is like writing HTML tags while treating them as JavaScript statements. Of course, this code takes place within some .js file itself. This isn’t HTML.

Note: How Dashboard Unity is really just an XML tag. It contains children, just as you would expect from any other standard XML code. The reason it works is that it’s processed by the JSX language processing mechanism. It’s a bit like learning a new language, but because it’s likely you already know HTML syntax, it’s not difficult to figure it out.

Example Explanation

The only primary difference is that curly brackets {} can now also be used right within JSX statements under tag attribute names. The whole tag Scoreboard is treated as an object. And its attribute scores are just its property which contains the value specified earlier in code by a JavaScript object scoreBoard, which is a JSON-literal object notation for creating objects.

This might seem a bit awkward at first, but this gives you tremendous control over your application. It unified document.getElement- Byrd (or jQuery equivalent of $(“#id”).act- tr(“scores”)) which is the method you would otherwise have to use just to access a property, into a new format. This format allows not only writing attributes directly into your HTML elements (as JSX) and assign them to already-existing variables/ objects, but also treat HTML as a JavaScript statement itself.

This is great, because of images that you can now return HTML code as a JavaScript statement from a function, and then it on to some other abstract method passing your application. It’s like tossing HTML between functions and preparing it for output in one of the containers in your application.

One more thing. You will notice that JSX uses className instead of just “class” as in traditional DOM object. The JSX docs explain it as “Since JSX is JavaScript, identifiers such as class and for are discouraged as attribute names.” So this is why the class has become class Name, and for has become htmlFor.

Writing React.js Applications

Welcome to the second part of React Gems. In this section, we are leaving the gem format behind us because the first part of the book was designed to simply get familiar with the most common principles of React programming and modern software development. This theory will help us investigate the practical aspects of programming with the React library. So let’s get going and start by writing our very first React component.

Writing your first React Component

Below you are seeing a compact example of what the very first React component you might write would look like. It simply renders the generic Hello World message into a DIV element. And it fits on just one line of code.

React.createClass({render: function() {
<div>Hello World.</div>
}) ;

Here, we are using the main React library object’s method createClass. This is how components are created. But what’s this code in blue? It looks like HTML, without double quotes surrounding it!
Components are usually stored in variables.

For Example:

var HelloWorld =React.createClass( {..} );

Storing components in variable names can help us later on when we create parent-child associations between our elements. Which is just a way to programmatically create relationships between nested components? Some of this code will appear a bit peculiar especially if you’re coming from a traditional JavaScript programmer background.

It’s the JSX code highlighted in blue that seems like it doesn’t fit in.
But remember that React programming is associated with using additional tools.

React library by itself is supposed to be just one part of your entire application. No one writes React apps using React library by itself. It’s just one single stone on the wall. In React we can write HTML inside JavaScript.

This is the reversal of the traditional “JavaScript inside HTML” idea we’ve gotten used to over the years, where we write JavaScript inside HTML attribute tags (like on click = “this.style.color=’red’;”) for example.

But React gives us the ability to do the opposite. We’ll find out why as we move forward. For now, let’s expand on creating components and then I’ll provide a brief explanation of how JSX helps us deal with blocks of HTML and treat them as return values.

Having said that… let’s move onto the complete example of creating your first React component and rendering its content within a specific HTML element:

// Add required library code
var React = react("react");
var ReactDOM = require("react-dom");
// Create your first react component "HelloWorld"
var HelloWorld - React.createClass({
render: function() {
Hello World
}) ;
// Draw "Hello World" component inside HTML element whose id is "app" ReactDOM.render(<HelloWorld />, docu document.getElementById("app"));

Notice that our newly created component HelloWorld has its own render method. But the ReactDOM object which acts as a primary rendering engine also has a render method of its own.

The correlation between the two is that ReactDOM.render calls render method of the component it’s passed as the first argument. Which, in this case, is our HelloWorld component.

Here, we first include the aforementioned React and ReactDOM libraries. You will be required to do that when starting a new reactive application from scratch. This is what initial is React?

Next, once we have to React included in our project, we will create a new instance of React class, using the React.createClass method.

This isn’t the only way to initialize a React app but we’ll stick to this example in this chapter. Finally, we call ReactDOM’s own method.render. And <HelloWorld/> here is the variable name HelloWorld we assigned the dinosaurs React code to. Basically, the React’s render method takes two arguments.

You simply pass what you want to render like the first argument and where you want to render it as the second (in this case it’s the HTML element whose ID is “app”.)

So from now on Whatever we assigned to HelloWorld variable will be rendered in an element like [div id “app”] and this is really the basic idea behind React programming. You build components and make them do things within specific HTML elements. Virtual DOM automatically takes care of fast rendering in the front view of your application.

But there is one more thing…

The HTML code highlighted in blue is the part that will be written into the component’s rendering area. Yes, we simply type HTML direct into JavaScript statements.

Again, this functionality is enabled by installing the JSX plugin from your node.js via babel. The process of setting this up is a bit complicated. But this is shown in more detail in my YouTube tutorials and also later in this book.

Congratulations on creating your first React component! I wanted to keep it simple and not overwhelm you with too much stuff that still needs to take place to set up React. But in my future chapters, we will continue to gradually unpack programming with React library and exactly just what it entails.