React - Element

About

An element is a node in the React tree (React DOM implementation).

A component being a user defined element returns an element.

Example

If you don't have any knowledge of React, check the getting started first.

Element are created with the createElement function. We create an alias/wrapper function called e around it to make the next code more concise.

var e =  function(type, props = [], ...children){
    return React.createElement(
       type,  // type is the string equivalent of the HTML tag (ie h1, div, ...)
       props, // props are the equivalent of HTML attributes 
       children // children are other react element or a string for a text node
);
}
  • A counter component with a useState hook to show how to call function
function Counter(props) {
    const [count, setCount] = React.useState(0); // state
    let updateCounter = function(){ setCount(count + 1) };
    return e(
        'div', // the type of element (div)
        {'className': 'container'}, // its properties
        e('h1', { className: 'H1'}, 'Welcome ', props.name), // first h1 child with two children text nodes
        e('p', null, 'A simple counter application'), // second p child
        e('p', null, "Counter: ", count), // third p child with two text nodes
        e( 
            'button',  // a button
            { onClick: updateCounter}, // on click call the function updateCounter
            'Increment' 
        )
    );
};
// Wrapping it to be able to use the state
let App = e(Counter, {name: "Foo"});
  • Result:

Type

A component will return:

Feature

Immutable

React elements are immutable.

Once you create an element, you can't change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.

Property

Attribute

All DOM properties and attributes (including event handlers) should have a camelCased name

For example, the HTML attribute tabindex corresponds to the attribute tabIndex in React. The exception is aria-* and data-* attributes, which should be lowercased.

Attribute value

Concatenate in Jsx Example:

<g transform={"translate("+margin.left+",0)"} />

Management

Create

The only element that you needs to create inside React is a component. html react element are built-in element.

The React.createElement() function 1) is the basic block to create element/component.

React.createElement(
  type, /* The node name */
  [props],
  [...children]
)

where:

React.createElement() performs a few checks to help write bug-free code but essentially it creates from

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

an object like this:

// Note: this structure is simplified
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world'
  }
};

Render

Update

Loop

Documentation / Reference


Powered by ComboStrap