Thinking in React – the foreman way
The purpose of this email is to provide a general overview of React and how
we are using it in foreman.
The Reactjs [1] component library was added to the foreman technology stack
[2] and used on the statistics page (charts) [3].
ReactReactjs is a view library that is concerned with the composing and
rendering of HTML components.
The main parts of react style programming are as follows:
virtual DOM
JSX
component lifecycle
props (immutable)
state (mutable)
React component composition model
Components
In its simplest form a React component takes in parameters, called props,
and returns a hierarchy of views to display via the render method” such
that the HTML is a projection of application state.
Creating React Components
There are many ways to create React components. In foreman we create
components either as ES6 class components or ES6 stateless functional
components.
ES6 Class Components
These components are created by extending React.Component and have
minimally a constructor and render method. They have lifecycle methods and
state. A state change causes the component and its children to be
re-rendered.
ES6 class component example,
class HelloWorld extends React.Component {
constructor(props) {
super(props);
// set initial state here
}
render() {
return (
<h1>Hello World</h1>
);
}
}
ES6 Stateless Functional Components
The ES6 stateless functional component is a stripped down version of the
ES6 class described above.
The function is very similar to the render method of an ES6 class
component, except that the function receives parameters as props.
ES6 stateless functional component example,
const HelloWorld = (props) =>
(
<h1>Hello World</h1>
);
Best practice is to use stateless functional components whenever possible.
Use ES6 class components when a feature not provided by a stateless
functional component (state, lifecycle methods, refs) is required.
Component Composition Container Components
Top level or container components implement logic. They are concerned with
behavior, marshalling data, and actions. They should have little or no
markup.
Container components pass data and actions down to their children and are
typically statelful.
Container components are best implemented as ES6 class components.
Presentation Components
Presentation components do not implement logic. They are mostly markup.
Presentation components receive the data and functions they need to render
markup from their parent.
Presentation components are best implemented as ES6 stateless functional
components.
[1] https://facebook.github.io/react/