Skip to content

Latest commit

 

History

History
99 lines (71 loc) · 1.89 KB

jsx.md

File metadata and controls

99 lines (71 loc) · 1.89 KB

A syntax extension to JS.



Example

const element = (
  <h1 className='greeting'>
    Hello, world!
  </h1>
)



JSX -> React Element

Babel compiles JSX to React.createElement() calls that evaluate to React elements.

The last example compiles (and is identical) to:

const element = React.createElement(
  'h1',
  { className: 'greeting' },
  'Hello, world!'
)

React.createElement() essentially creates an object as in the React element example.



More

JSX... :

  • Helps separate concerns (rather than technologies) with React components that contain both markup and logic.

  • Allows React to show more useful error and warning messages.

  • Prevents injection attacks - It is safe to embed user input in JSX.

    const title = response.potentiallyMaliciousInput
    // This is safe:
    const element = <h1>{title}</h1>



Usage Tips

  • You can put any valid JS expression inside the {} in JSX. JSX is an expression too.

    const name = 'Josh Perez'
    const element = <p>Hello, {name}</p>
  • Wrapp multi-line JSX in () to avoid auto ; insertion.

    return (
      <p>
        Hello, {formatName(user)}!
      </p>
    )
  • You may also use {} to embed a JS expression in an attribute.

    const element = <img src={user.avatarUrl}></img>
  • React DOM uses camelCase property naming convention. E.g., class -> className. tabindex -> tabIndex.

  • JSX allows self-closing for any tag (<img />, <MyComponent />).




Prev - React Elements | Next - Rendering Elements