react-controller
react-controller
is a component for React that takes a path, fetches a JSON response, and passes the object to its child component. Page caching, custom loading screens, prefetching and server-side rendering are made incredibly easy, especially when paired with react-router
.
Installation
$ npm i react-controller --save
The UMD build is also available on unpkg:
When using the UMD build, you can find the library on window.ReactController
.
Basic Usage
This simplified example will make an XHR request to /api/product/foo-bar
and pass the resulting JSON object to the Child
component. Until the request is returned, the ProductLoading
component will be rendered.
<Controller path="/api/product/foo-bar" loadingComponent=ProductLoading> <Product /></Controller>
Props
-
path
string
(Required)
The endpoint to request data from. -
children
function
orReactElement
(Required)
Can be either a typical React element or a function. -
cache
boolean
(Default: false)
Setting totrue
will store all previously requested path data in theController
state. -
initialProps
object
(Default: null)
If the app is server rendered, pass the ininitialProps
to avoid an extra XHR request when theController
component mounts. -
loadingComponent
function
(Default: null)
The React component that should render while the requested path is loading. -
onError
function
A function that will be called if the requested path returns anything other than a 200 header. -
forceReload
boolean
(Default: false)
If cache is turned on, but a certain path should always make an XHR request to the server, setforceReload
totrue
. -
isStatic
boolean
(Default: false)
If the child component doesn’t need to make an XHR request to the server to render, then setisStatic
totrue
. -
options
object
(Default: {})
Object containing parameters for the request. (See the fetch spec.)
Handling Errors
There are two different ways to handle errors. The first is to pass a function into the onError
prop of the Controller
component. If no error occurs, then the object returned from your path will be spread across your child component's props.
const ErrorHandler = <div>status status header</div> const App = <Controller path="/api/product/foo-bar" onError=ErrorHandler> <Product /> </Controller>
The second, option is to pass a function
as the children
prop of Controller
. This allows you to choose to pass only specific parts of the returned object.
const ErrorHandler = <div>status status header</div> const App = <Controller path="/api/product/foo-bar"> error ? <ErrorHandler status=errorstatus /> : <Product ...props /> </Controller>
Prefetching
If you would like to prefetch a page, use the this.context.controller.prefetch()
function.
static contextTypes = controller: PropTypesobjectisRequired { thiscontextcontroller } ...
Example
To run the example application, run these commands from inside the /example
directory.
$ npm i
$ npm start
View the example at http://localhost:3000.