DEV Community

Shawn Smith
Shawn Smith

Posted on

JSX in React

JSX in React is used to create DOM elements in JavaScript in an efficient way.

JSX is an extension for JavaScript and describes the look of the user interface. It allows us to define React elements using syntax that looks similar to HTML. In JSX, an element’s type is specified with a tag. The tag’s attributes represent the properties. The element’s children can be added between the opening and closing tags.

import React from 'react';
import ReactDOM from 'react-dom/client';

function App() {
  const firstName = 'Shawn'
  const lastName = 'Smith'
  return (
    <h1>Hello {firstName} {lastName}!</h1>
  )
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />); 
Enter fullscreen mode Exit fullscreen mode

This code is some simple JSX. We have a first and last name variables declared; Then we are creating a h1 tag that would display this information by writing the variables in curly braces inside of the tag.

You can put any valid JavaScript expression inside the curly braces in JSX. It will pull in the constant firstName into the HTML written. This output will render the message “Hello Shawn Smith” on the web page.

Image description

In vanilla JavaScript we would use document.createElement() to create pieces of our DOM in JavaScript which was a messier process than what we have access to with JSX in React.

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

Top comments (0)