SyntaxStudy
Sign Up
React JSX Expressions and Dynamic Content
React Beginner 1 min read

JSX Expressions and Dynamic Content

One of JSX's greatest strengths is the ability to interpolate arbitrary JavaScript expressions directly into markup. Anything wrapped in `{}` is evaluated and rendered: numbers, strings, arrays, function call results, and ternary expressions all work. React automatically converts numbers and strings to text nodes, renders arrays of JSX elements sequentially, and ignores `null`, `undefined`, and `false` — a handy property for conditional rendering. String values rendered as JSX are HTML-escaped by default, which protects against cross-site scripting (XSS). If you genuinely need to inject raw HTML — for example from a trusted content management system — React provides the `dangerouslySetInnerHTML` prop, whose name is intentionally alarming. Computed class names, dynamic style objects, and attribute values are all set through expressions. A common pattern is to build a class string conditionally — for instance `className={isActive ? 'btn active' : 'btn'}` — or to use a utility like `clsx` or `classnames` for complex cases. Mastering expression interpolation is the key to making JSX feel as expressive as a templating language while retaining full JavaScript power.
Example
import { useState } from 'react';

function DynamicContent() {
  const [isActive, setIsActive] = useState(false);
  const [count, setCount] = useState(3);

  const items = ['React', 'Vue', 'Angular'];
  const today = new Date().toLocaleDateString();

  return (
    <div>
      {/* String expression */}
      <p>Today is {today}</p>

      {/* Arithmetic */}
      <p>Double count: {count * 2}</p>

      {/* Function call */}
      <p>Upper: {items[0].toUpperCase()}</p>

      {/* Ternary for conditional text */}
      <p>Status: {isActive ? 'Active' : 'Inactive'}</p>

      {/* Dynamic className */}
      <button
        className={isActive ? 'btn btn-active' : 'btn'}
        onClick={() => setIsActive(a => !a)}
      >
        Toggle
      </button>

      {/* Rendering an array */}
      <ul>
        {items.map((item, i) => (
          <li key={i}>{item}</li>
        ))}
      </ul>

      {/* null / false are silently ignored */}
      {false && <p>This never renders</p>}
      {null}
      {count > 10 && <p>Big number!</p>}
    </div>
  );
}

export default DynamicContent;