JSX

Using React.createElement() is very verbose, so most of the time we use JSX, a syntax extension to JavaScript. React brings HTML and JS together into an unholy creation called JSX. JSX allows us to write code that looks like HTML inside of our JavaScript but is eventually compiled down to JavaScript objects.

const AdoptionListing = ({ name, imageURL }) => {
  return (
    <div className="kitten">
      <h3>{name}</h3>
      <img src={imageURL} alt="Kitten" />
      <p>Kitten - available for adoption</p>
    </div>
  );
};

const App = () => {
  return (
    <>
      <AdoptionListing name="Mittens" imageURL="http://placekitten.com/200/150" />
      <AdoptionListing name="Bobo" imageURL="http://placekitten.com/201/150" />
      <AdoptionListing name="Mickey" imageURL="http://placekitten.com/202/150" />
    </>
  );
};

JSX is not valid JavaScript - but it is transpiled/compiled into valid JavaScript.

JSX Rules & Conventions

  • JSX can only render one top level element but that element can contain numerous children.

  • All tags need to be closed. Self-closing tags like <img> need to be written as <img />.

  • Any JavaScript within JSX must be enclosed in curly braces {}.

  • The keyword class is reserved so the class attribute must be renamed to className. There are other differences between HTML attributes and JSX. We'll get to those when we need them, but className is the first and most used one we'll encounter.

References

Last updated