Henry's blog

React Tutorial #2 - JSX

This blog post will be about JSX and what you can do with them.

What is JSX

In my understanding, JSX is a representation of your UI and an XML esque language to define your UI.

The difference is while HTML is static, with JSX you can embed values of variables within the defined UI. Something like a UI template that you'd see in Angular or Vue with its templating engine or .NET MVC with its cshtml or something like handlebars.

Each of them has its own syntax for different ways to do templating. However, with JSX you almost don't need to learn anything new if you already know JavaScript. As JavaScript syntax will basically work right out of the box within the enclosure of curly brackets { }.

One important thing to note when using JSX is whatever is evaluated in the curly braces will be rendered in the UI (considering it is valid JSX).

What can we do with JSX

Enough talk, why don't we look at some stuff we can do with JSX?

With JSX we can do conditional rendering

export default function App() {
  const [open, setOpen] = useState(true);
  return (
    <div>
      { open ? <p>Now you see me</p> : <p>Now you don't</p> }
      <button onClick={() => setOpen(o => !o)}>toggle</button>
    </div>
  );
}

We easily render multiple elements with JSX

const fruits = ["apple", "orange", "banana"];

export default function App() {
  return (
    <div>
      <h3>Fruit basket</h3>
      <ul>
        {fruits.map((fruit) => <li key={fruit}>{fruit}</li>)}
      </ul>
    </div>
  )
};

Or we can display dynamic values within the UI.

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h3>Counter app</h3>
      <p>Current count: {count}</p>
      <button onClick={() => setCount((count) => count + 1)}>
        increment
      </button>
      <button onClick={() => setCount((count) => count - 1)}>
        decrement
      </button>
    </div>
  )
}

Conclusion

In this blog post, we have learned what JSX are and what can you do with JSX. If you wish to learn more about JSX, I would recommend the React beta docs, or React official docs to learn JSX in depth.

#jsx #react #tutorial