DEV Community

Muhammad Medhat
Muhammad Medhat

Posted on

Jsx Vs Plain JavaScript in React Apps

Are you new to React and wondering what the difference is between JSX and plain JavaScript?

Firstly, let's talk about JSX. It's an extension to JavaScript that allows you to write HTML-like code within your JavaScript code. This is great for creating complex UI components in React without having to write a lot of code. However, it can be a bit confusing if you're not used to it.

On the other hand, plain JavaScript is the primary programming language used in React. It's used for creating and manipulating components, handling user input, and managing the state of the application. It's a versatile language that can be used for a wide range of tasks, both in and outside of React.

So, what's the difference between the two? Well, the main difference is the syntax. JSX uses a syntax that's similar to HTML, while JavaScript uses a more traditional syntax. For example, to create an element in JSX, you can use HTML tags like this:

const element = <div>Hello, world!</div>;
Enter fullscreen mode Exit fullscreen mode

But in plain JavaScript, you'd create the same element like this:

const element = document.createElement('div');
element.innerHTML = 'Hello, world!';

Enter fullscreen mode Exit fullscreen mode

Another difference is the way components are defined. In JSX, you create components by writing functions that return JSX. For example:

function Greeting(props) {
  return <div>Hello, {props.name}!</div>;
}
Enter fullscreen mode Exit fullscreen mode

And to use this component, you'd simply render it like this:

const element = <Greeting name="John" />;
Enter fullscreen mode Exit fullscreen mode

In plain JavaScript, you'd create the same component like this:

function Greeting(props) {
  const element = document.createElement('div');
  element.innerHTML = `Hello, ${props.name}!`;
  return element;
}
Enter fullscreen mode Exit fullscreen mode

And to use it, you'd render it like this:

const element = Greeting({ name: 'John' });
document.body.appendChild(element);
Enter fullscreen mode Exit fullscreen mode

As you can see, JSX simplifies the process of creating components in React by allowing you to write HTML-like code within JavaScript.

In summary, JSX is an extension to JavaScript that simplifies the process of building user interfaces in React, while plain JavaScript is the primary programming language used in React. Both have their uses, but JSX is recommended as it makes building UI components a lot easier. I hope this helps clear things up for you!

Top comments (0)