React - Component (User-defined Element)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

A component is a special element in the React tree.

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

Conceptually, components are like JavaScript functions. They:

  • accept arbitrary inputs (called props)
  • return React elements describing what should appear on the screen.

In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. See Conditional rendering

Advertising

3 - Syntax

Functional vs Class

A valid React component:

  • accepts a single props object argument with data and returns a React element.
  • has a name starting with a capital letter (In order to detect a DOM tag from a React tag. For example, <div/> represents a DOM tag, but <Welcome/> represents a component and requires Welcome to be in scope.
  • must return a single root element. Generally, a <div> is added to contain all the others element.



The two below syntax's are equivalent:

Class Component

class Welcome extends React.Component {
 
   // Optional. Needed to set state
  constructor(props) {
     super(props); // Always call the base constructor with props.
  }
 
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
 
}

Feature only available to class

Advertising

4 - Type

4.1 - Parent/Child

4.2 - Universal

Native and Web: Tweet and Blog Announcing styled-components/primitives: Create truly universal @reactjs component systems!

5 - Hierarchy

6 - Management

6.1 - Create

6.1.1 - Jsx

Element are created generally from a JSX expression that compiles to the createElement function.

6.1.2 - createElement

The React.createElement() is the basic block to create 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'
  }
};
Advertising

7 - Design: Extracting Components

A good rule of thumb is that if a part of your UI:

  • is used several times (Button, Panel, Avatar),
  • or is complex enough on its own (App, FeedStory, Comment),

it is a good candidate to be a reusable component.

8 - Documentation Creation / Workbench

Documentation of Component and creations testing framework are called Workbench. List of Workbench

Workbench:

Doc:

9 - Libary

9.1 - Component

9.1.1 - Date

9.1.2 - Vis

9.2 - icon

10 - Documentation / Reference