Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

https://github.com/danwang/retainer


https://github.com/danwang/retainer

Last synced: about 1 month ago
JSON representation

Lists

README

        

# Retainer

![badge](https://img.shields.io/badge/🔥-Blazing%20Fast-red.svg)
![badge](https://img.shields.io/badge/λ-Functional-blue.svg "Code functions and works as expected")
![badge](https://img.shields.io/badge/🏢-Enterprise%20Grade-999999.svg "With six nines of CSS hex color codes")

Retainer (_React_ + _container_) is a small tool to compose [render prop components](https://reactjs.org/docs/render-props.html).

# Installation

```
yarn add @danwang/retainer
```

# Usage

A `Consumer` is a React component that accepts a single prop `children` of
type `(T) => ReactNode`.

A `Retainer` is a container wrapping a `Consumer` with methods for
transforming the provided values.

A typical flow looks like:

1. Put the component in a `Retainer`
2. Transform the `Retainer`
3. Extract a component or ReactElement from the `Retainer`

# Example

Using the context API (React 16.3+):

```jsx
import * as Retainer from "@danwang/retainer";

const Context = React.createContext({
value: 0,
setValue: () => () => {}
});

class App extends React.Component {
state = { value: 0 };
handleSetValue = (value: number) => () => this.setState({ value });
render() {
const context = {
value: this.state.value,
setValue: this.handleSetValue
};
return (



);
}
}

const Root = () =>
Retainer.make(Context.Consumer)
.map(context => (


Count is {context.value}
+

))
.toReactElement();

ReactDOM.render(, element);
```

# API

## Creation

### `Retainer.make: (component: Consumer) => Retainer`

Creates a `Retainer` containing the component.

## Transformation

### `Retainer.map: (mapper: (T) => U) => Retainer`

Applies a function to the provided value of the interior component.

### `Retainer.flatMap: (mapper: (T) => Retainer) => Retainer`

Applies a function returning a `Retainer` to the provided value of the interior
component, flattening one level of nested `Retainer`s.

## Extraction

### `Retainer.toComponent: () => Consumer`

Returns a render prop component that provides the interior value.

### `Retainer.toReactElement: () => ReactElement`

If the interior type is a `ReactElement`, returns a `ReactElement` which, when
mounted, mounts necessary `Consumer` components to render the interior value.