Dorokhov.codes

04. Creating elements

Example:

const elem = <h2 className="greeting">Hello, world!</h2>;

In fact, Babel just compiles JSX into calls React.createElement(). So we could write the same using a native function:

const elem = React.createElement('h2', {className: 'greeting'}, 'Hello, world!');

The elem object looks like this inside:

const elem = {
    type: 'h2',
    props: {
        className: 'greeting',
        children: 'Hello, world!'
    }
};

Rules

If we use more than one tag we should use parentheses.

const elem = (
    <div>
        <h2>Hello, world!</h2>
        <input type="text" />
        <button />
    </div>
);

Any element show have only one parent element.

Reserved words:

  • Instead of the class attribute use className.
  • Instead of the for attribute use htmlFor.
  • All other attributes are written using camel-case (tabIndex instead of tabindex).
  • There’s a special attribute for inputs: defaultValue.

Working with variables

Inside { ... } we can use any expressions.

const elem = (
    <div>
        <h2>{text}</h2>
    </div>
);

Tricks

Instead of:

const items = data.map(({name, salary}) => {
    return <EmployeesListItem name={name} salary={salary} />
});

Use:

const items = data.map(item => {
    return <EmployeesListItem {...item} />
});

Another option for destructuring:

const items = data.map(item => {
    const {id, ...props} = item;
    return <EmployeesListItem key={id} {...props} />
});