0
0
Vueframework~5 mins

JSX in Vue components

Choose your learning style9 modes available
Introduction

JSX lets you write HTML-like code inside JavaScript. In Vue, it helps you build components using JavaScript syntax instead of templates.

You want to use JavaScript logic directly inside your component's render output.
You prefer writing UI with JavaScript instead of Vue's template syntax.
You need to create dynamic elements or lists with complex conditions.
You want to reuse UI pieces as JavaScript functions easily.
You are integrating Vue with other JavaScript libraries that use JSX.
Syntax
Vue
import { defineComponent } from 'vue';

export default defineComponent({
  setup() {
    return () => (
      <div>Hello JSX in Vue!</div>
    );
  }
});

JSX code goes inside the return () => ( ... ) function in setup().

Use parentheses ( ) to wrap JSX elements for clarity.

Examples
Simple JSX returning a heading element.
Vue
export default {
  setup() {
    return () => <h1>Title with JSX</h1>;
  }
};
JSX with JavaScript expression inside curly braces to show a variable.
Vue
export default {
  setup() {
    const name = 'Vue';
    return () => <p>Hello, {name}!</p>;
  }
};
JSX rendering a list using map() with keys for each item.
Vue
export default {
  setup() {
    const items = ['Apple', 'Banana', 'Cherry'];
    return () => (
      <ul>
        {items.map(item => <li key={item}>{item}</li>)}
      </ul>
    );
  }
};
Sample Program

This Vue component uses JSX to show a count and a button. Clicking the button increases the count. It uses ref for reactive state and onClick for the button event.

The button has an aria-label for accessibility.

Vue
import { defineComponent, ref } from 'vue';

export default defineComponent({
  setup() {
    const count = ref(0);
    const increment = () => {
      count.value++;
    };
    return () => (
      <div>
        <p>Count: {count.value}</p>
        <button onClick={increment} aria-label="Increment count">Add 1</button>
      </div>
    );
  }
});
OutputSuccess
Important Notes

JSX in Vue requires a build step with tools like Vite or Vue CLI configured to support JSX.

Use onClick (camelCase) for event handlers in JSX, not lowercase onclick.

Always add key props when rendering lists to help Vue track elements efficiently.

Summary

JSX lets you write HTML-like code inside JavaScript functions in Vue components.

It is useful for dynamic UI and when you prefer JavaScript over templates.

Remember to use return () => ( ... ) in setup() and wrap JSX in parentheses.