JSX in React

666


JSX:

JSX stands for JavaScript XML which is used to write HTML tags in Javascript.

So we use this to describe what the UI is going to look like. Once we implement the component using JSX we need to pass this code through babel which is compiler for modern browsers.

Babel will convert our code into plain JavaScript code which browser can understand.

Click this URL and check how babel converts react code into JavaScript
https://babeljs.io/repl

So using react we don't need to write HTML files separately we can include HTML tags in JavaScript and babel will take care of conversions.

Let us look at the example React code with JSX and without.

** With JSX:**

class Counters extends React.component{
   state = {};
   render() {
    return  (
      <h1> {this.props.name} increments counter <h1>
    )
  }
}

ReactDOM.render(
<Counters name = "Madhav"/>, document.getElementById("root"));

Below the Counters class, there is React DOM Render function which is calling the Counters component(<Counters />) and specifies where (root) your React code will be printed.w

Without JSX:


class Counters extends React.component{
   state = {};
   render() {
    return  (
      React.createElement('h1', null, ${this.props.name} increments counter)
    )
  }
}

ReactDOM.render(
React.createElement(Counters, {name: "Madhav"}, null), document.getElementById("root"));

This gives the exact output as react code with javascript. So its no mandatory to use JSX in react but using JSX it simplifies the JavaScript code.

** Some important points of JSX**

  • We cannot pass more than one element using JSX. So there must be parent tag in which we can include tags as we can.
class Counters extends React.component{
   state = {};
   render() {
    return  (
      <div>
       <h1> {this.props.name} increments counter <h1>
       <p> Hi </p> 
      </div>
    )
  }
}
  • We can use if conditions and for loops using JSX

class Movies extends Component {
  state = {
    movies: getMovies()
  };
  render() {
    if (this.state.movies.length === 0) {
      return <p>There are no movies available</p>;
    }
    else {
      return <p>There are 8 movies in database</p>
    }
  }
}
  • Some of the HTML attributes will change like class becomes className why because class is registered keyword in JavaScript.