Bharath Bharath - 2 months ago 13
React JSX Question

React.component return method is confusing

So I'm trying to learn React.js and I'm starting off by reading from Tutorials Point. I created the sample React app as per their instructions and it came out pretty well.

My question is, I saw this

React.component()
method declaration here in the App.jsx file. They have returned actual HTML code inside a return method. I've never seen this kind of return statement before.

class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}


It doesn't even return it as a string or an object (Correct me if I'm wrong here).

If someone could explain this, I would greatly appreciate it.

Answer

The HTML looking syntax is not actually HTML and not all HTML properties will work in it. It is JSX, JSX is a preprocessor step that adds XML syntax to JavaScript. For example if you try to use class as a property in the .JSX file it will not actually apply your CSS class:

class App extends React.Component {
   render() {
      return (
         <div class="cssClass">
            Hello World!!!
         </div>
      );
   }
}

You must do this. Notice class is now className

class App extends React.Component {
   render() {
      return (
         <div className="cssClass">
            Hello World!!!
         </div>
      );
   }
}

You do not have to use the JSX syntax to write React applications but it makes it a little more readable. You can read more about it here. ReactJS will grab this syntax and render it into HTML elements. Also here are some gotchas that make it different from HTML.

Comments