React elements

As described here, "Elements are the smallest building blocks of React apps". Under the hood, JSX compiles to regular JavaScript, and React's createElement is used to return an object representation of a virtual DOM element. But, in JSX this object just looks like regular HTML. You can use React elements inside JavaScript anywhere JavaScript expressions can be used, which means stored as a variable, returned from a function, stored in an object, array, or rendered inside JSX.

In this example, we show three examples storing elements inside variables. Elements can live anywhere JavaScript expressions can live.

It's important to note that in most cases, you should be using a functional component instead to return elements, rather than storing elements in variables around your app. You can see this practice here- BetterDescription is a real component rendered within the JSX, whereas getDescription is simply a function that returns an element.

Menu
Lesson 10/22
const myTask = "Swab the deck!";

const elements = {
  footer: <footer> Created by The Captain. </footer>,
};

// Function that returns an Element.
// Tip: This can just be a component
function getDescription() {
  return <p> Managing my tasks at sea </p>;
}

// This is a function that returns an Element, but it's used as a component
function BetterDescription() {
  return <p> This is a better description because it's a component </p>;
}

export default function App() {
  // Inline Element Expression
  const header = <h1> 🏴‍☠️ The Captain's Tasks </h1>;
  // Element returned from function
  const description = getDescription();
  // Element pulled from object
  const footer = elements["footer"];

  return (
    <>
      {header}
      {description}
      <BetterDescription />
      <ul>
        <li> {myTask} </li>
        <li> Discover {3 + 2} treasure chests </li>
      </ul>
      {footer}
    </>
  );
}