React: Difference between revisions

1,432 bytes added ,  1 October 2019
→‎How React Works: rendering array of elements
Line 1,409: Line 1,409:
ReactDOM.render([dish, dessert], document.getElementById("root"));
ReactDOM.render([dish, dessert], document.getElementById("root"));
</source>
</source>
== Children ==
<source lang="js">
React.createElement(
  "ul",
  null,
  React.createElement("li", null, "2 lb salmon"),
  React.createElement("li", null, "5 sprigs fresh rosemary"),
  React.createElement("li", null, "2 tablespoons olive oil"),
  React.createElement("li", null, "2 small lemons"),
  React.createElement("li", null, "1 teaspoon kosher salt"),
  React.createElement("li", null, "4 cloves of chopped garlic")
);
// equivalent to
const items = [
  "2 lb salmon",
  "5 sprigs fresh rosemary",
  "2 tablespoons olive oil",
  "2 small lemons",
  "1 teaspoon kosher salt",
  "4 cloves of chopped garlic"
];
React.createElement(
  "ul",
  { className: "ingredients" },
  items.map((ingredient, i) => React.createElement("li", { key: i }, ingredient))
);
</source>
== React Components ==
<source lang="js">
function IngredientsList({ items }) { // destructure items from props
  return React.createElement(
    "ul",
    { className: "ingredients" },
    items.map((ingredient, i) => React.createElement("li", { key: i }, ingredient)
  );
}
const items = [
  "2 lb salmon",
  "5 sprigs fresh rosemary",
  "2 tablespoons olive oil",
  "2 small lemons",
  "1 teaspoon kosher salt",
  "4 cloves of chopped garlic"
];
ReactDOM.render(
  React.createElement(IngredientsList, { items }, null),
  document.getElementById("root")
);
</source>
use functions to create components because class syntax is being deprecated.


= React with JSX =
= React with JSX =