Skip to content

Commit eb19b8f

Browse files
committed
Add support for React Context
* See https://reactjs.org/docs/context.html
1 parent 9501881 commit eb19b8f

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/React/Basic.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,3 +218,11 @@ exports.toReactComponent = function(_unionDict) {
218218
};
219219
};
220220
};
221+
222+
exports.createContext = function(defaultValue) {
223+
var context = React.createContext(defaultValue);
224+
return {
225+
consumer: context.Consumer,
226+
provider: context.Provider
227+
};
228+
};

src/React/Basic.purs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ module React.Basic
2121
, ReactComponentInstance
2222
, toReactComponent
2323
, Ref
24+
, ReactContext
25+
, createContext
26+
, provider
27+
, consumer
2428
) where
2529

2630
import Prelude
@@ -369,6 +373,46 @@ foreign import toReactComponent
369373
-> { render :: Self props state -> JSX | spec }
370374
-> ReactComponent { | jsProps }
371375

376+
type ReactContext a =
377+
{ provider :: ReactComponent { value :: a, children :: Array JSX }
378+
, consumer :: ReactComponent { children :: a -> Array JSX }
379+
}
380+
381+
-- | Create a `ReactContext` given a default value. Use `provider` and `consumer`
382+
-- | to provide and consume context values. Alternatively, use the fields of
383+
-- | `ReactContext` directly if a `ReactComponent` is required for interop.
384+
-- |
385+
-- | ```purs
386+
-- | render self =
387+
-- | R.div_
388+
-- | [ R.button
389+
-- | { onClick: capture_ $ self.setState \s -> s { counter = s.counter + 1 }
390+
-- | , children: [ R.text "Tick!" ]
391+
-- | }
392+
-- | , provider countContext self.state.counter
393+
-- | [ consumer countContext \counter ->
394+
-- | [ R.text $ "Ticks: " <> (show counter)
395+
-- | ]
396+
-- | ]
397+
-- | ]
398+
-- | ```
399+
-- |
400+
-- | __*See also:* `provider`, `consumer`, React's documentation regarding Context__
401+
foreign import createContext :: forall a. a -> ReactContext a
402+
403+
-- | Create a provider `JSX` given a context value and children.
404+
-- |
405+
-- | __*See also:* `createContext`, `consumer`__
406+
provider :: forall a. ReactContext a -> a -> Array JSX -> JSX
407+
provider context value children =
408+
element context.provider { value, children }
409+
410+
-- | Create a consumer `JSX` from a context value to children.
411+
-- |
412+
-- | __*See also:* `createContext`, `producer`__
413+
consumer :: forall a. ReactContext a -> (a -> Array JSX) -> JSX
414+
consumer context children =
415+
element context.consumer { children }
372416

373417
-- |
374418
-- | Internal utility or FFI functions

0 commit comments

Comments
 (0)