React JS Class Components with Class Instances

React JS Class Components with Class Instances: We’ll speak about components a lot more throughout the rest of the book. They are the building blocks of your react application. But remember that this is “React on the palm of your hand” section!

Let’s briefly overview the full scope of a React component, its options, and methods available by default in the React library. Components are defined by createClass method existing on the main React object:

React JS Class Components Example

var MyComponent = React.createClass({
displayName: 'MyComponent',
/* This is the core of your React Class
options and lifecycle methods will be written
here /
render: function() {
// Once rendered, let's return a newly created
element
return React.createElement(/.../);
}
}) ;

Component Options

Components hold the propTypes object and two methods that return an object:



  • propTypes object mapping prop names to types
  • getDefaultProps function returning an object
  •  getInitialState function returning object

Life cycle Methods

  • componentWillMount
  •  componentDidMount
  • componentWillReceiveProps
  • shouldComponentUpdate
  •  component will update.
  • componentDidUpdate
  • component will unmount

These 7 methods can be implemented in your React class. Not all components classes will require using all of the seven functions. This will depend on your component’s purpose.

Each is basically an event that executes at a particular time during the lifecycle of a React component. Most of this functionality is to do with checking to mount and update the state of the component.

In addition to these methods, of course, you can also add your own custom functions, depending on what your component is supposed to be doing.

React JS Component Instances

Component instances are the instantiated objects from the class representation we’ve just taken a look in the previous section. Here are a few hints as to their implementation:

Component Instances Implementation

1. The “this” keyword within a component refers to itself.

2. Stateless functional components do not have component instances.

3. One component instance may persist over multiple equivalent React Elements.

Component Instances Properties

1. Property this.props contains any props passed to React.createElement through tag attributes

2.  this.state property contains a state set by setState and getInitialstate methods.

Methods

1. setState(changes) applies the given changes to this.state for rerendering the DOM component.

2. forceUpdate() immediately rerenders the component to the DOM.

In this section, I will present several “gems” that expand on reactive programming with a few explanations of important principles. Each gem is a focused discussion on a particular subject.