Codepath

JSX

JavaScript Syntax Extension (JSX) is a React extension to JavaScript which provides a way to structure UI in a declarative way using familiar syntax to HTML. It’s goal is to allow developers to describe what the UI should look like, rather than how it should get updated.

React does not require the use of JSX, but most people find it useful to work with a familiar UI syntax inside a JavaScript code.

With JSX

importReactfrom'react'

functionHello(){
  return(
		<divclassName="hello">
      CodePath.org
    </div>
  )
}

exportdefaultHello;

Without JSX

importReactfrom'react'

functionHello=()=>{
  returnReact.createElement(
    'div',
    {className:'hello'},
   'CodePath.org'
  )
}

exportdefaultHello;

In general, JSX should feel very natural and because it’s a superset of JavaScript, you are able to use all of JavaScript existing features within the markup.

That said, there are a few things to keep in mind about syntax in JSX:

  • Uses camelCase naming convention for HTML attributes.

    E.g: tabindex becomes tabIndex

    <div tabIndex={-1}></div>
  • Some HTML attributes have alternative names.

    E.g: The HTML class attribute is classNames

    <div className="Button" />
  • JavaScript expressions need to be wrapped in single curly braces { }

    const isBackgroundRed = true;
    
    <div className={isBackgroundRed ? 'background-red' : 'background-blue'} />
  • empty tags need to be close with />, ie:

    const element = <img src={user.avatarUrl} />;
  • You can not use both quotes (for string values) and curly braces (for expressions) in the same attribute.

  • By default React escapes values embedded in JSX before rendering. This means, everything is converted to a string before being render.

    Try embedding HTML into a React component

    const heading = "<h1>Heading</h1>";
    
    const App = () => (
      <div>{heading}</div>
    );

    React treats the heading const as a string and displays

    <h1>Heading</h1>

  • for JavaScript and JSX code to be properly highlighted in your editor, you need to use “Babel” language definition.

  • To display a list of items, every item needs a unique identifier to be passed within the JSX key attribute

    const todoItems = todos.map((todo) =>
      <li key={todo.id}>
        {todo.text}
      </li>
    );
  • There is no single prescribed solution for CSS styling.

React doesn’t prescribe a single solution for CSS. Here are a few options:

  • CSS files. You can load them in your index.html page header for common global layouts, styles & fonts.
  • CSS modules. Locally scope CSS files imported directly in your JavaScript files. You’ll need a properly configured loader. Create React App enables this by default
Fork me on GitHub