What exactly is going on with JSX?
Hands down the most confusing thing about react isn’t react at all. It’s this code I am typing right here and it looks like HTML but I know it’s not a string because I am not wrapping it in quotes.
Head over to my browser and open up a new tab : go to babeljs.io/repl
The right panel which shows me the output after it’s run through Babel.
So to get started, I am going to recreate some of this functionality over inside of the left panel.
*And inside of Atom I could open up index.html. I am indeed running app through Babel.
- First ,I’m going to define my new class
The new class is called “Greeter” , and I set it equal to React.createClass.
- Now let’s go ahead and define render method
It’s going to be a function that takes no arguments.
- All render does it return some JSX to render to the browser. Starte with a very simple example inside of return parentheses.
I’m going to type H1 tag with the word Hello World. And on the right could see something very different than what I have on the left. Every time use JSX in files they get converted to call to React.createElement.
After Babel transpiling JSX code to React.creactElement, below was called with tag name. And for any attributes I currently don’t have any define and the contents in this case it’s just the string Hello World!
- Go ahead and render this to the screen (Use ReactDom.render)
I’m going to pass some JSX code which is going to be the “Greeter” component just like this.
And the second argument is document.getElenentById(‘app’).
Notice that over in the right inside of our call to ReactDom.render another call to React.createElement was placed. This one was called with two arguments. The first is the tag name only it’s not a string like it was up here. This time it’s using the variable “Greeter” which stores are react component. And the second argument “null” is going to be empty because I haven’t passed anything to it.
- Copy and past “app.jsx” content in Atom to Babel to show the final result
I’m going to go into Atom and copy entire app.jsx file and paste it in the left panel. On the right you can see what we have is one call to React.createElement with div tag and its attributes which are null.
And then as the other arguments I have two more calls to React.createElement, one is H1 tag and two is <p> tag.
- Now the final I were going to prove that inside of Atom is to comment (command+/) current return statement inside of render
Return a call to React.createElement. Create an H1 element. It doesn’t need any actual attributes so I’ll leave that null. The next thing I’m going to do is add the contents and do inside of strings is “Hello React.createElement”.
- Now if I save the file and refresh my browser
My app works just the same. So whether using JSX code or calls to React.createElement. It’s all doing the same thing in the end.