Skip to content

Latest commit

 

History

History
87 lines (73 loc) · 3.13 KB

08-react-understand-and-use-interpolation-in-jsx.md

File metadata and controls

87 lines (73 loc) · 3.13 KB

08. Understand and Use Interpolation in JSX

Notes

  • Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
  • Let’s write a React component that has some conditional logic in it to explore the interpolation characteristics of JSX syntax:
<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">
    function CharacterCount({ text }) {
      // this is JavaScript land
      return (
        // inside of the brackets it's React land
        <div>
          {/* this is all JavaScript land  */}
          {`The text "${text}" has `}
          {/* this is a conditional (ternary) operator */}
          {/* This operator is frequently used as a shortcut for the if statement */}
          {text.length ? <strong>{text.length}</strong> : 'No'}
          {' characters'}
        </div>
        // this is JavaScript land
      );
    }

    const element = (
      <>
        <CharacterCount text="Hello World" />
        <CharacterCount text="" />
      </>
    );

    ReactDOM.render(element, document.getElementById('root'));
  </script>
</body>
  • Inside the curly braces, it's JavaScript land, but it's limited to only expressions.
  • Interpolation is not unique to React or JavaScript, we also see it in HTML when we use script tags or style tags.
<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">
    function CharacterCount({ text }) {
      return (
        <div>
          {/* this is all JavaScript land  */}
          {/* but it's limited to only expressions that evaluate to some value */}
          {/* no loops, switch, or if statements  */}
          {`The text "${text}" has `}
          {text.length ? <strong>{text.length}</strong> : 'No'}
          {' characters'}
        </div>
      );
    }

    const element = (
      <>
        <CharacterCount text="Hello World" />
        <CharacterCount text="" />
      </>
    );

    ReactDOM.render(element, document.getElementById('root'));
  </script>
</body>

Additional resource