Introduction to JSX in React

  • JSX stands for JavaScript XML
  • React uses JSX for templating instead of JavaScript
  • JSX produces React “elements”
  • JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() or appendChild() methods
  • JSX is an extension of the JavaScript language based on ES6, and is translated into regular JavaScript at runtime.

JSX

JSX allows us to write HTML directly within the JavaScript code.

const myelement = <h1>Welcome to JSX</h1>;

ReactDOM.render(myelement, document.getElementById('root'));

Without JSX

const myelement = React.createElement('h1', {}, 'Without JSX!');

ReactDOM.render(myelement, document.getElementById('root'));

JSX Expressions

const myelement = <h1> Addition of  {"Two Numbers"} {25} and {35} is:  {25 + 30}  </h1>;

ReactDOM.render(myelement, document.getElementById('root'));

Specifying Children with JSX

const myelement = (
  <div>
    <h1>Start of Days List</h1>
    <ol>
    <li>Sunday</li>
    <li>Monday</li>
    <li>Tuesday</li>
    <li>Wednesday</li>
    <li>Thursday</li>
    <li>Friday</li>
    <li>Saturday</li></ol>
    <h1>End of Days List</h1>
  </div>
);

ReactDOM.render(myelement, document.getElementById('root'));

Embeding the result of calling a JavaScript function

function displayName(user) {
  if (user) {
  return user.firstName + ' ' + user.lastName;
  }  
  return <h1>Hello, Stranger.</h1>;

}
const user = {
  firstName: 'Girish',
  lastName: 'Chandra'
};

const element = (
  <h1>
    Hello, {displayName(user)}!
  </h1>
);

ReactDOM.render(element, document.getElementById('root'));

Specifying Attributes with JSX

const imageurl = "https://www.xyzzz.com/images/logo-wide.png";
const elementimg = <img src={imageurl}></img>;

ReactDOM.render(elementimg, document.getElementById('root'));

Styling

var myStyle = {
  fontSize: 50,
  fontFamily:'Courier New',
  color: 'red'
}
const myelement = (
      <div>
          <h1 style = {myStyle}>Hello My Style</h1>
      </div>
);
ReactDOM.render(myelement, document.getElementById('root'));

Write all above examples in index.js file and use the below index.html file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

References

  • https://reactjs.org/docs/introducing-jsx.html

Learn more about Components and Props in the next blog article series.

Happy Learning!