Add React-context example project

This commit is contained in:
Juho Teperi 2020-03-28 14:07:24 +02:00
parent 83c0cdd698
commit c54d6891cf
4 changed files with 91 additions and 0 deletions

View File

@ -45,6 +45,11 @@ Reagent syntax follows [React Fragment short syntax](https://reactjs.org/docs/fr
container)
```
[Context example project](../examples/react-sortable-hoc/src/example/core.cljs)
better explains how
`:>` or `adapt-react-class` convert the properties to JS objects,
and shows how to use Cljs values with context.
Alternatively you can use the [static contextType property](https://reactjs.org/docs/context.html#classcontexttype)
```cljs

View File

@ -0,0 +1,28 @@
(defproject reagent/react-context-example "0.1.0"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.597"]
[reagent "0.10.0"]
[figwheel "0.5.19"]
[cljsjs/react-sortable-hoc "1.11.0-0"]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.19"]]
:figwheel {:repl false
:http-server-root "public"}
:profiles {:dev {:resource-paths ["target/cljsbuild/client" "target/cljsbuild/client-npm"]}}
:cljsbuild
{:builds
{:client
{:source-paths ["src"]
:figwheel true
:compiler {:parallel-build true
:source-map true
:optimizations :none
:main "example.core"
:output-dir "target/cljsbuild/client/public/js/out"
:output-to "target/cljsbuild/client/public/js/main.js"
:asset-path "js/out"
:npm-deps false}}}})

View File

@ -0,0 +1,13 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<div id="app">
<h1>Reagent example app see README.md</h1>
</div>
<script src="js/main.js"></script>
</body>
</html>

View File

@ -0,0 +1,45 @@
(ns example.core
(:require [reagent.core :as r]
[reagent.dom :as rdom]
[react :as react]
[goog.object :as gobj]))
(defonce my-context (react/createContext "default"))
(def Provider (.-Provider my-context))
(def Consumer (.-Consumer my-context))
(defn children []
[:> Consumer {}
(fn [v]
(r/as-element [:div "Context: " (pr-str v)]))])
(defn root []
;; Provider takes props with single property, value
;; :< or adapt-react-class converts the Cljs properties
;; map to JS object for the Provider component.
[:div
[:> Provider {:value "bar"}
[children]]
;; :> and adapt-react-class convert the props
;; recursively to JS objects, so this might not be
;; what you want.
[:> Provider {:value {:foo "bar"}}
[children]]
;; To yourself control how the props are handled,
;; use create-element directly.
;; Properties map needs to be JS object here, but now the
;; value is used as is, Cljs map.
;; Note that you need to convert children from Reagent markup
;; to React elements yourself.
(r/create-element Provider
#js {:value {:foo "bar"}}
(r/as-element [children]))])
(defn start []
(rdom/render [root] (js/document.getElementById "app")))
(start)