DEV Community

Temitope Ayodele
Temitope Ayodele

Posted on

What is JSX?!

JSX is a XML like syntax extension for JavaScript. It was created by a team at Facebook. It is cool because it allows you to combine the view with the functionality, hence simplifying the developer's experience. It is a syntax extension of JavaScript. It is used in React, though not exactly compulsory, but it comes in useful to be able to work with the UI inside the JavaScript code. In React, you can easily loosely couple both the markup and the logic into a simple unit(Component) using JSX. One of the reasons people like React is because of JSX, because JSX is easier to write and understand than creating and appending many elements in vanilla JavaScript.

JSX is closer to JavaScript, not HTML, so there are a few key differences to note when writing it.

  • 'class' is a JavaScript reserved keyword, so to add a CSS class in JSX, 'className' is used instead of 'class'.
  • Properties and methods in JSX are camelCase - onsubmit will become onSubmit.
  • Self-closing tags must end in a slash - e.g.

This is an example of what JSX looks like.

const name = 'Temitope';
const element = <h1 className="hello">Hello, {name}</h1>;
Enter fullscreen mode Exit fullscreen mode

You wrap the JavaScript elements inside curly braces. JSX allows all of JavaScript's language features, so can be used in functions, if-statements, for-loops, assigned to variables, used as an argument, can be a return value of a JavaScript function.

const exactLocation = (user) => {
  return user.state + ' ' + user.country;
}
const greetUser = (user)=>{
  if(user){
    return <h1>Hello, {user.name}. How is {exactLocation(user)} today?</h1>;
  }
  return <h1>Hello, I don't know you</h1>
}

const user = {
  name: 'Temitope',
  state: 'Lagos',
  country: 'Nigeria'
};

const element = (
  <h1>
    {user.name} is from {exactLocation(user)}!
    {greetUser(user)}
  </h1>
);



ReactDOM.render(
  element,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

JavaScript expressions are put within curly braces in JSX.

In the code snippet above, the JavaScript function is embedded inside the HTML tags using curly braces. To ensure better readability, JSX is splitted over multiple lines, and to prevent automatic semicolon insertion, it is better to put them in parenthesis(as seen above).

There is a set of transpilers that all conform to the JSX syntax, but they use different semantics on the output.

  1. React JSX: Create React Elements using JSX.
  2. jsx-transform
  3. Babel: includes support for transpiling JSX right out of the box.

Top comments (0)