Skip to content
This repository has been archived by the owner on Jul 10, 2020. It is now read-only.

Latest commit

 

History

History
64 lines (51 loc) · 2.54 KB

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

File metadata and controls

64 lines (51 loc) · 2.54 KB

04. Use JSX effectively with React

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