Choose between JSX or JavaScript in React

Choose between JSX or JavaScript in React

  • JSX vs. JavaScript
  • React Component Lifecycle

JSX is one of the most commonly used syntaxes for React, which allows us to embed JavaScript statements and expressions in HTML. But what if we don’t need JSX? Let’s understand the difference between JSX and JavaScript!
First, JSX allows us to embed JavaScript expressions in HTML, which is helpful for dynamically generating HTML content. For example, we can use JavaScript expressions to insert data into a template string:

const greeting = 'Hello, world!';
<div>{greeting}</div>

In pure JavaScript, you need to manually concatenate strings:

const greeting = 'Hello, world!';
document.body.innerHTML = '<div>' + greeting + '</div>';

Secondly, JSX supports custom tags, which makes it easier for us to understand and identify components. For example, we can create a MyComponent component and then use it in JSX like this:

<my-component />

In JavaScript, we must call the constructor explicitly:

new MyComponent().mount(document.body);

Finally, JSX provides some useful features such as conditional rendering and loop rendering. For example, we can easily render different elements based on conditions:

{
    
    condition ? <div>True</div> : <div>False</div>}

In JavaScript, you need to write the if statement manually:

if (condition) {
    
    
  const element = document.createElement('div');
  element.innerText = 'True';
} else {
    
    
  const element = document.createElement('div');
  element.innerText = 'False';
  document.body.appendChild(element);
}

Although JSX is more intuitive and concise, in some cases, we may still want to use JavaScript instead of JSX. At this point you can use the jsx-to-js tool, which converts JSX to JavaScript as follows:

jsx-to-js('<div>{hello}</div>') // ->
createElement('div', null, hello)

In short, JSX is the most commonly used language for React, but it is not required. If you like JavaScript, you can choose to use the jsx-to-js tool to convert JSX to JavaScript so that you can use JavaScript code in React.
Life cycle of React components

Guess you like

Origin blog.csdn.net/weixin_46002631/article/details/134317247