react-compose-state
A helper function to attach state to stateless function components.
Background
Since React v0.14, stateless function components are supported, which allows you to write a component as a pure function. This is very handy with ES2015 and JSX. Here is an example.
const Hello = <div>Hello name!</div>;
It is recommended to use stateless components as much as possible, and once you are used to it, you might want to avoid writing class-based components. Class-based components are powerful and you can mange lifecycles of components, but the state is one of what is required often, especially if using an external store (like Flux) is not an option.
This package provides an easy way to add state to statelss components.
This avoids the use of this
which is also known as thisless javascript.
Install
npm install react-compose-state --save
Usage
One liner:
;; const Counter = <div> <span>Count: counter</span> <button onClick= >Click</button> </div>;
With PropTypes:
;;; const Counter = <div> <span>Count: counter</span> <button onClick= >Click</button> </div>); CounterpropTypes = counter: PropTypesnumberisRequired setCounter: PropTypesfuncisRequired const initialState = counter: 1 ; initialStateCounter;
With options:
;;; const Counter = <div> <span>Count: counter</span> <button onClick= >Click</button> </div>); CounterpropTypes = counter: PropTypesnumberisRequired updateCounter: PropTypesfuncisRequired const initialState = counter: 1 ;const options = setters: counter: 'updateCounter' ; initialState optionsCounter;
Example
The example folder contains a working example. You can run it with
PORT=8080 npm run example
and open http://localhost:8080 in your web browser.