Skip to content

Latest commit

 

History

History
70 lines (52 loc) · 2.57 KB

04-react-use-jsx-effectively-with-react.md

File metadata and controls

70 lines (52 loc) · 2.57 KB

05. Use JSX effectively with React

MHF Notes

Egghead Notes

  • JSX is not an entirely different language, but it is a bit of an extension to the language, so knowing how you would express certain JavaScript things within the JSX syntax is important to using JSX effectively.
  • To interpolation use { }. Any JavaScript expression inside of the curly braces will be evaluated and passed to the React.createElement API. This allows you to be expressive when building out UI's. Example:
<script type="text/babel">
  const rootElement = document.getElementById('root');
  // declaring variables
  const children = 'Hello World';
  const className = 'container';
  // interpolation
  const element = <div className={className}>{children}</div>;
  ReactDOM.render(element, rootElement);
</script>

Since this is JSX and not HTML, you can use self-closing tags:

<script type="text/babel">
  const rootElement = document.getElementById('root');
  const children = 'Hello World';
  const className = 'container';
  const props = { children, className };
  // self-closing tags
  const element = <div {...props} />;
  ReactDOM.render(element, rootElement);
</script>
  • The spread operator takes either an array or an object and expands it into its set of items. We can use the spread operator to pass down our props to the React.createElement API:
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
  <script type="text/babel">
    const rootElement = document.getElementById('root');
    const children = 'Hello World';
    const className = 'container';
    const props = { children, className };
    // using spread operator
    const element = <div {...props} />;
    ReactDOM.render(element, rootElement);
  </script>
</body>
  • You can also add or extended props in a declarative and deterministic way.

Additional resource