summary: Learn how to extend and customise the technologies we use for application state and client-rendered UI.
# Introduction to the "React" layer
Some admin modules render their UI with React, a popular Javascript library created by Facebook.
For these sections, rendering happens via client side scripts that create and inject HTML
declaratively using data structures.
There are some several members of this ecosystem that all work together to provide a dyanamic UI. They include:
* [ReactJS](https://facebook.github.io/react/) - A Javascript UI library
* [Redux](http://redux.js.org/) - A state manager for Javascript
* [GraphQL](http://graphql.org/) - A query language for your API
* [Apollo](https://www.apollodata.com/) - A framework for using GraphQL in your application
All of these pillars of the frontend application can be customised, giving you more control over how the admin interface looks, feels, and behaves.
First, a brief summary of what each of these are:
## React
React's job is to render UI. Its UI elements are known as "components" and represent the fundamental building block of a React-rendered interface. A React component expressed like this:
This syntax is known as JSX. It is transpiled at build time into native Javascript calls
to the React API. While optional, it is recommended to express components this way.
### Recommended: React Dev Tools
The [React Dev Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) extension available for Chrome and Firefox is critical to debugging a React UI. It will let you browse the React UI much like the DOM, showing the tree of rendered components and their current props and state in real time.
## Redux
Redux is a state management tool with a tiny API that affords the developer highly predictable behaviour. All of the application state is stored in a single object, and the only way to mutate that object is by calling an action, which is just a simple object that describes what happened. A function known as a _reducer_ mutates the state based on that action and returns a new reference with the updated state.
The following example is taken from the [Redux Github page](https://github.com/reactjs/redux):
```js
// reducer
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
let store = createStore(counter)
store.subscribe(() =>
console.log(store.getState())
)
// Call an action
store.dispatch({ type: 'INCREMENT' })
// 1
```
### Recommended: Redux Devtools
It's important to be able to view the state of the React application when you're debugging and
building the interface.
To be able to view the state, you'll need to be in a dev environment
and have the [Redux Devtools](https://github.com/zalmoxisus/redux-devtools-extension)
installed on Google Chrome or Firefox, which can be found by searching with your favourite search
engine.
## GraphQL and Apollo
[GraphQL](http://graphql.org/learn/) is a strictly-typed query language that allows you to describe what data you want to fetch from your API. Because it is based on types, it is self-documenting and predictable. Further, it's structure lends itself nicely to fetching nested objects. Here is an example of a simple GraphQL query:
The above query is almost self-descriptive. It gets a user by ID, returns his or her name and email address, along with the title of any blog posts he or she has written, and the first five comments for each of those. The result of that query is, very predictably, JSON that takes on the same structure.
On its own, GraphQL offers nothing functional, as it's just a query language. You still need a service that will invoke queries and map their results to UI. For that, SilverStripe uses an implementation of [Apollo](http://dev.apollodata.com/) that works with React.
## For more information
This documentation will stop short of explaining React, Redux, and GraphQL/Apollo in-depth, as there is much better
documentation available all over the web. We recommend:
* [The Official React Tutorial](https://facebook.github.io/react/tutorial/tutorial.html)
* [Build With React](http://buildwithreact.com/tutorial)
* [Getting Started with Redux](https://egghead.io/courses/getting-started-with-redux)
* [The React Apollo docs](http://dev.apollodata.com/react/)
# The Injector API
Much like SilverStripe's [Injector API](../../extending/injector) in PHP,
the client-side framework has its own implementation of dependency injection
known as `Injector`. Using Injector, you can register new services, and
transform existing services.
Injector is broken up into three sub-APIs:
*`Injector.component` for React UI components
*`Injector.reducer` for Redux state management
*`Injector.form` for forms rendered via `FormSchema`.
The frontend Injector works a bit differently than its backend counterpart. Instead of _overriding_ a service with your own implementation, you _enhance_ an existing service with your own concerns. This pattern is known as [middleware](https://en.wikipedia.org/wiki/Middleware).
Middleware works a lot like a decorator. It doesn't alter the original API of the service,
but it can augment it with new features and concerns. This has the inherent advantage of allowing all thidparty code to have an influence over the behaviour, state, and UI of a component.
## A simple middleware example
Let's say you have an application that features error logging. By default, the error logging service simply outputs to `console.error`. But you want to customise it to send errors to a thirdparty service. For this, you could use middleware to augment the default functionality of the logger.
Now, let's add some middleware to that service. The signature of middleware is:
```js
(next) => (args) => next(args)
```
Where `next()` is the next customisation in the "chain" of middleware. Before invoking the next implementation, you can add whatever customisations you need. Here's how we would use middleware to enhance `LoggingService`.
```js
import thirdPartyLogger from 'third-party-logger';
We haven't overriden any functionality. `LoggingService(error)` will still invoke `console.error`, once all the middleware has run. But what if we did want to kill the original functionality?
```js
import LoggingService from './LoggingService';
import thirdPartyLogger from 'third-party-logger';
Much like the configuration layer, we need to specify a name for this transformation. This will help other modules negotiate their priority over the injector in relation to yours.
The second parameter of the `transform` argument is a callback which receives an `updater`object. It contains four functions: `component()`, `reducer()`, `form.alterSchema()` and `form.addValidation()`. We'll cover all of these in detail functions in detail further into the document, but briefly, these update functions allow you to mutate the DI container with a wrapper for the service. Remember, this function does not _replace_
the service -- it enhances it with new functionality.
### Helpful tip: Name your component middleware
Since multiple enhancements can be applied to the same component, it will be really
useful for debugging purposes to reveal the names of each enhancement on the `displayName` of
the component. This will really help you when viewing the rendered component tree in
[React Dev Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en).
For this, you can use the third parameter of the `updater.component` function. It takes an arbitrary
Sometimes, it's critical to ensure that your customisation happens after another one has been executed. To afford you control over the ordering of transforms, Injector allows `before` and `after` attributes as metadata for the transformation.
This flag can only be used once per transformation.
The following are not allowed:
*`{ before: ['*', 'something-else'] }`
*`{ after: '*', before: 'something-else' }`
</div>
## Injector context
Because so much of UI design depends on context, dependency injection in the frontend is not necessarily universal. Instead, services are fetched with context.
To apply context-based transformations, you'll need to know the context of the component you want to customise. To learn this,
open your React Developer Tools (see above) window and inspect the component name. The
context of the component is displayed between two square brackets, appended to the original name, for example:
`TextField[TextField.AssetAdmin.FileEditForm.Title]`. The context description is hierarchical, starting
with the most general category (in this case, "Admin") and working its way down to the most specific
category (Name = 'Title'). You can use Injector to hook into the level of specificity that you want.
# Customising React components with Injector
When middleware is used to customise a React component, it is known as a [higher order component](https://facebook.github.io/react/docs/higher-order-components.html).
Using the `PhotoItem` example above, let's create a customised `PhotoItem` that allows a badge, perhaps indicating that it is new to the gallery.
Forms in the React layer are built declaratively, using the `FormSchema` API. A component called `FormBuilderLoader` is given a URL to a form schema definition, and it populates itself with fields (both structural and data-containing) and actions to create the UI for the form. Each form is required to have an `identifier` property, which is used to create context for Injector when field components are fetched. This affords developers the opportunity provide very surgical customisations.
### Updating the form schema
Most behavioural and aesthetic customisations will happen via a mutation of the form schema. For this, we'll use the `updater.form.alterSchema()` function.
The `alterSchema()` function takes a callback, with an instance of `FormStateManager` (`form` in the above example) as a parameter. `FormStateMangaer` allows you to declaratively update the form schema API using several helper methods, including:
Validation for React-rendered forms is handled by the [redux-form](http://redux-form.com) package. You can inject your own middleware to add custom validation rules using the `updater.form.addValidation()` function.
Before starting this tutorial, you should become familiar with the concepts of [Immutability](https://www.sitepoint.com/immutability-javascript/) and [Redux](http://reduxjs.org).
The examples use [Spread in object literals](http://redux.js.org/docs/recipes/UsingObjectSpreadOperator.html) which is at this moment in Stage 3 Proposal. If you're more comfortable with using
the `Object.assign()` API that shouldn't present any problems and should work the same.
For example:
```js
newProps = { ...oldProps, name: 'New name' };
```
is the same as
```js
newProps = Object.assign(
{},
oldProps,
{ name: 'New name' }
);
```
To start customising, you'll need to transform an existing registered reducer, you can find what reducers are registered by importing Injector and running `Injector.reducer.getAll()`
As you can see, we use the `reducer()` function on the `update` object to augment Redux state transformations.
### Using Redux dev tools
It is important to learn the basics of [Redux dev tools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en), so that you can find out what ACTIONS and payloads to intercept and modify in your Transformer should target.
Most importantly, it helps to understand the "Action" sub-tab on the right panel (bottom if your dev tools is small), as this will be the data your Transformer will most likely receive, pending other transformers that may run before/after your one.
### Structuring a transformer
We use currying to supply utilities which your transformer may require to handle the transformation.
-`originalReducer` - reducer callback which the transformer is customising, this will need to be called in most cases. This will also callback other transformations down the chain of execution. Not calling this will break the chain.
-`getGlobalState` - A function that gets the state of the global Redux store. There may be data outside the current scope in the reducer which you may need to help determine the transformation.
We can easily define a new initial state by providing the `state` param with a default value.
It is recommended to keep the call for the original initialState for your initialState then override values, so that you do not lose any potentially critical data that would have originally been set.