-
Notifications
You must be signed in to change notification settings - Fork 58
/
going-further-reactR.Rmd
823 lines (663 loc) · 30.8 KB
/
going-further-reactR.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
# Shiny and React with {reactR} {#going-further-reactR}
[React](https://reactjs.org/) is an open-source library designed to quickly develop user interfaces or UI components, on the __front end__.
It has been developed by [Facebook](https://github.com/facebook/react) and the community (more than 1500 contributors) and made public in May 2013. It is currently used worldwide and has around 163 k stars on the GitHub ranking and widely impacts the mobile market, through the [React Native](https://reactnative.dev/) library. __React__ is also really convenient to develop attractive documentations with [docusaurus](https://v2.docusaurus.io/).
If you ever have built user interfaces with pure JS, you might like React!
Below, we give a short introduction to the React ecosystem and see how we can benefit from it from the R Shiny side. By the end of this chapter, you'll be able to develop R interfaces to some nice React libraries like the Argon design [system](https://demos.creative-tim.com/argon-design-system-react/?_ga=2.179634850.760978196.1612189904-282783983.1612189904#/), shown Figure \@ref(fig:argon-design-react).
```{r argon-design-react, echo=FALSE, fig.cap='Argon design template with React.', out.width='100%'}
knitr::include_graphics("images/going-further/argon-design-react.png")
```
As another example, `{reactable}` is an HTML widget developed on top of the [`react-table`](https://github.com/tannerlinsley/react-table) library.
## Quick introduction to React
To understand React, there are few prerequisites, notably basic HTML/CSS/JS knowledge, especially JS modules (see section \@ref(about-js-modules)). However, if you managed to reach this chapter, you should not worry too much.
### Setup
__Node__ and __npm__ are required. If you are not sure, run:
```{r, echo=FALSE, results='asis'}
tmp_code <- "node -v
npm -v"
code_chunk_custom(tmp_code)
```
At that stage it is also good to have [`yarn`](https://classic.yarnpkg.com/en/docs/install#mac-stable), as we'll need it for `{reactR}`.
If nothing is returned, please refer to section \@ref(install-node). To initiate a React [project](https://create-react-app.dev/), we leverage the [`npx`](https://docs.npmjs.com/cli/v7/commands/npx) command:
```{r, echo=FALSE, results='asis'}
tmp_code <- "npx create-react-app <PROJECT_NAME>"
code_chunk_custom(tmp_code)
```
Replace `<PROJECT_NAME>` by the real name of your project. If this seems intimidating,
keep in mind this is the same concept that the `{golem}` [package](https://github.com/ThinkR-open/golem) uses to initiate the creation of robust Shiny projects, except that we work from the terminal.
Once done (the package initialization takes some time),
move to the project folder and launch the demo app:
```{r, echo=FALSE, results='asis'}
tmp_code <- "cd <PROJECT_NAME> && npm start"
code_chunk_custom(tmp_code)
```
If you have yarn, `yarn start` also works.
You should see something similar to Figure \@ref(fig:basic-react-app).
```{r basic-react-app, echo=FALSE, fig.cap='npm start opens the React app.', out.width='50%', fig.align='center'}
knitr::include_graphics("images/going-further/basic-react-app.png")
```
Congrats! You are running your first React app.
### Basics
We are now all set up to start learning the basics of React. Among all created files,
notice the `/src/app.js` file. Inside the `App` function, we remove all the content inside
the `return` statement to put a simple `<h1>Hello, world!</h1>` HTML title. We also clean the imports
as we don't need any CSS and logo anymore. We obtain:
```{r, echo=FALSE, results='asis'}
jsx_code <- "function App() {
return (
<h1>Hello, world!</h1>
);
}
// don't remove, this is needed by index.js
export default App; "
code_chunk_custom(jsx_code, "jsx")
```
Once done, we run `npm build` (or `yarn build`), to rebuild the JS code and `npm start` to
restart the server and preview the app. In practice, once the server is launched, there is
no need to restart it whenever the code is updated. A simple save will refresh the interface!
The code you see above is a React __component__. The definition is rather simple: it is a function that returns a rather complex piece of UI. How are components rendered by React?
So far, we didn't have a look at the `/src/index.js` script. Inside we find:
```{r, echo=FALSE, results='asis'}
jsx_code <- "ReactDOM.render(
App,
document.getElementById('root')
);"
code_chunk_custom(jsx_code, "jsx")
```
::: {.noteblock data-latex=""}
Recent versions of `npx create-react-app` have `<React.StrictMode><App /></React.StrictMode>` instead of `App`, which does the same thing. You may also find `<App />`. In practice, we rarely modify this part.
:::
In short, this inserts the `App` component inside the element having __root__ as id in the main
HTML page. This HTML skeleton may be found in the `public/index.html` folder. You may imagine that at the end of the day, our app will be composed of multiple bricks and call `ReactDOM.render` on the top-level component.
#### About JSX
We just wrote our first React component. Didn't you notice something weird in that code?
JS and HTML are mixed, in what we called __JSX__, that is a syntax extension to JS. JSX makes the code
less verbose, for instance:
```{r, echo=FALSE, results='asis'}
js_code <- "React.createElement(
'h1',
'Hello, world!'
);"
code_chunk_custom(js_code, "js")
```
does exactly the same thing as above but when the code becomes more complex, it is nearly
impossible to read.
Let's see how to pass variables into JSX. We want to show `Hello, <Your Name>`, we store
the name in a variable and modify the `app.js` code accordingly:
```{r, echo=FALSE, results='asis'}
jsx_code <- "function App() {
const name = 'David';
return (
<h1>Hello, {name}</h1>
);
}"
code_chunk_custom(jsx_code, "jsx")
```
Expressions are passed within curly brackets `{expression}` and you may even call functions inside.
Tag attributes also require curly brackets. Let's modify the title tag to give it a color and
a size.
```{r, echo=FALSE, results='asis'}
jsx_code <- "function App() {
const name = 'David';
return (
<h1 style={color: 'red', fontSize: 40}>Hello, {name}</h1>
);
}"
code_chunk_custom(jsx_code, "jsx")
```
Try to save. Why does this fail? We can't pass multiple object properties inside a single `{}`.
We need either double brackets like `{{object properties: values, ...}}` or to store the object in
a variable before:
```{r, echo=FALSE, results='asis'}
jsx_code <- "function App() {
const name = 'David';
return (
<h1 style={{color: 'red', fontSize: 40}}>Hello, {name}</h1>
);
}
// OR
function App() {
const name = 'David';
const myStyle = {
color: 'red',
fontSize: 40
}
return (
<h1 style={myStyle}>Hello, {name}</h1>
);
}"
code_chunk_custom(jsx_code, "jsx")
```
Notice that we write CSS properties following the __camelCase__ syntax, `font-size` being equivalent to `fontSize`.
#### Combining components {#react-map}
The whole interest is to combine multiple components to create reusable pieces. We edit the above code
to create a `SayHello` component. Notice the __props__ parameter. It is a way to pass configuration from the parent component. In that case, we want to display the person name, that is `props.name`. In the meantime, we edit the `App` parent component and call `SayHello` three times, passing a different name like `<SayHello name="David" />` (this is the reason why we recover `props.name` in the lower-level component):
```{r, echo=FALSE, results='asis'}
jsx_code <- "function SayHello(props) {
return (
<h1>Hello, {props.name}</h1>
);
}
function App() {
return(
<>
<SayHello name=\"David\" />
<SayHello name=\"Lisa\" />
<SayHello name=\"Simon\" />
</>
);
}"
code_chunk_custom(jsx_code, "jsx")
```
::: {.noteblock data-latex=""}
Notice the enclosing `<>...</>`. This is called a React __fragment__ and useful if we don't want to
insert any extra `<div>` in the DOM.
:::
We could be even more efficient by leveraging the lists capabilities. We create an array
of names and apply the `map` method to return the corresponding `<SayHello />` sub-component:
```{r, echo=FALSE, results='asis'}
jsx_code <- "const names = ['David', 'Lisa', 'Simon'];
function App() {
const sayHelloToAll = names.map(
(name) => <SayHello key={name} name={name} />
);
return(sayHelloToAll);
}"
code_chunk_custom(jsx_code, "jsx")
```
::: {.warningblock data-latex=""}
By convention, all elements inside a `map` require __keys__.
:::
__Props__ are __read-only__ and must not be modified within their own component. How do we update components then?
#### Component state {#react-hooks}
A component __state__ is private and controlled by this same component. Since React 16.8 and the introduction of __hooks__, this is not necessary to convert the component function to a [class](https://reactjs.org/docs/components-and-props.html#function-and-class-components).
The easiest example to illustrate hooks capabilities is the button. Each time, we click on a button,
we want to keep the current number of clicks in a state, like the `actionButton()`. We start by
importing the `useState` function from `react` and create a new `ActionButton` component.
Inside, we set the state with `useState`, which creates the state variable `count`, as well as the function to update it, namely `setCount`. This way to create two variables at once is called array __destructuring__. We set the initial number of counts to 0:
```{r, echo=FALSE, results='asis'}
jsx_code <- "import {useState} from 'react';
function ActionButton() {
const [count, setCount] = useState(0);
}"
code_chunk_custom(jsx_code, "jsx")
```
Next step is to create the button skeleton. We provide an `onClick` property that updates
the button state. Inside, we write an anonymous function, which calls `setCount` and increments
the count value by 1. At this point, you may replace the `app.js` content by:
```{r, echo=FALSE, results='asis'}
jsx_code <- "import {useState} from 'react';
function ActionButton() {
const [count, setCount] = useState(0);
return(
<button onClick={() => setCount(count + 1)}>
Number of clicks: {count}
</button >
);
}
function App() {
return (
<ActionButton />
);
}
export default App;"
code_chunk_custom(jsx_code, "jsx")
```
We may improve the previous app and add a reset button within the `ActionButton` component that
sets the count back to 0:
```{r, echo=FALSE, results='asis'}
jsx_code <- "function ActionButton() {
const [count, setCount] = useState(0);
return(
<>
<button onClick={() => setCount(count + 1)}>
Number of clicks: {count}
</button >
<button onClick={() => setCount(0)}>
Reset
</button >
</>
);
}"
code_chunk_custom(jsx_code, "jsx")
```
It would make more sense to only show the reset button once the button has been clicked at least once. We define the `isResetVisible` variable which is `true` whenever the
count is higher than 0 and `false` if the count is 0, leveraging the JS __ternary__ operator. We store the reset button in a variable and only return something if `isResetVisible` is `true`:
```{r, echo=FALSE, results='asis'}
jsx_code <- "function ActionButton() {
const [count, setCount] = useState(0);
const isResetVisible = count > 0 ? true : false;
let resetButton;
if (isResetVisible) {
resetButton = <button onClick={() => setCount(0)}>
Reset
</button >
}
return (
<>
<button onClick={() => setCount(count + 1)}>
Number of clicks: {count}
</button >
{resetButton}
</>
);
}"
code_chunk_custom(jsx_code, "jsx")
```
That's all folks! Now that you get a better understanding of how React works, let's see how to use it with Shiny.
## Introduction to `{reactR}`
::: {.importantblock data-latex=""}
This section has been written and tested with `{reactR}` `0.4.4`.
Some features may change in future releases.
:::
In this part, we see how to leverage `{reactR}` [@R-reactR] to bring a few component from the `reactstrap` [library](https://reactstrap.github.io/) to Shiny.
To install `{reactR}`:
```{r, eval=FALSE}
# stable from CRAN
install.packages("reactR")
# lastest from GitHub
remotes::install_github("react-R/reactR")
```
In the following, we are going to propose an implementation of the `reactstrap` button, which is a Bootstrap 4 and React-powered action button.
### Setup
`{reactR}` exposes the `scaffoldReactShinyInput()`, which sets the necessary pieces of code to get started with the input development (see Figure \@ref(fig:reactR-init-input)):
- An `<input_name>.R` file containing the input skeleton as well as its related update function, located in the `./R` folder.
It also creates a custom HTML dependency pointing to the input JS logic.
- A `jsx` file with a boilerplate to start developing the input JS logic, located in the `./srcjs` folder.
- A `package.json` file containing dependencies.
- An `app.R` file to host the input demonstration code.
- A `webpack.config.js` file (discussed later).
- Classic R package files like `DESCRIPTION`, `.Rbuildignore`...
Interestingly, the `.Rbuildignore` contains a few lines to ignore non-standard files and folders like `srcjs` and `package.json`.
Besides, providing an optional dependency with a name and version taken from __npm__ installs all necessary dependencies in the `package.json` file:
```{r, eval=FALSE}
path <- file.path(tempdir(), "reactstrapTest")
usethis::create_package(path, rstudio = TRUE)
# Wait new project to be created before running
# the following!!!
reactR::scaffoldReactShinyInput(
"action_button",
list(
"reactstrap" = "^8.9.0"
)
)
```
```{r reactR-init-input, echo=FALSE, fig.cap='Package initialization with {reactR}.', out.width='100%'}
knitr::include_graphics("images/going-further/reactR-init-input.png")
```
Note that `{reactR}` provides __webpack__ as JS code manager. To __build__ the JS code, we go to the RStudio terminal tab (or any terminal) and run at the package root:
```{r, echo=FALSE, results='asis'}
tmp_code <- "yarn install
yarn run webpack --mode=development"
code_chunk_custom(tmp_code)
```
This installs all dependencies listed in the `package.json` file and creates a `package-lock.json` file. If you ever used `{renv}`, this is very similar and guarantees isolation of your package. All dependencies are stored in the `node_modules` folder.
The `run webpack` command compiles the JS in production-ready code. Should you need to customize the build pipeline, the webpack configuration is located in `webpack.config.js`. On the R side, the generated JS file is referenced in HTML dependencies, located in the `<input_name>.R` file.
If you specify the `--mode=development` tag, it falls back to development code.
In the following, we see how to customize the newly created component.
### Customize the R logic
A `{reactR}` input is composed of R and JS code that both exchange information. Upon initialization, we obtained a `.R/action_button.R` code:
```{r, eval=FALSE}
action_buttonInput <- function(inputId, default = "") {
reactR::createReactShinyInput(
inputId,
"action_button",
htmltools::htmlDependency(
name = "action_button-input",
version = "1.0.0",
src = "www/reactstrapTest/action_button",
package = "reactstrapTest",
script = "action_button.js"
),
default,
list(),
htmltools::tags$span
)
}
```
For convenience, we remove the input suffix to name it `action_button`.
Overall, this function calls `reactR::createReactShinyInput()` that:
- Gives the widget a class and id. The class is targeted on the JS side (see \@ref(reactR-jsx-logic)) and is necessary to make it working.
- Sets all necessary dependencies (React, ...), as well as the internal JS code (see section \@ref(reactR-jsx-logic)).
- Creates the input HTML code with `{htmltools}`.
- Sets the default value, through the `default` parameter.
- Allows passing a list of options inside the `list()` container. By default, nothing is sent but we will use it very soon.
We also have the corresponding update input function, which we renamed to `update_action_button()` for consistency:
```{r, eval=FALSE}
update_action_button <- function(session, inputId, value,
configuration = NULL) {
message <- list(value = value)
if (!is.null(configuration)) {
message$configuration <- configuration
}
session$sendInputMessage(inputId, message);
}
```
In Shiny, the end user cannot decide what is the initial value of an action button. It is always set to 0 by default. Therefore, we decided to remove the default parameter from `action_button()` and make it 0 by default.
In order to add a label and change the button color, we introduce two extra parameters and
add them to the configuration list:
```{r, eval=FALSE}
action_button <- function(
inputId,
label,
status = "primary"
) {
reactR::createReactShinyInput(
# ... unchanged ...
default = 0,
configuration = list(
label = label,
status = status
),
htmltools::tags$div
)
}
```
Let's see below how to make this interactive with some JSX code.
### Implement the JS logic {#reactR-jsx-logic}
It's time to develop the logic. For now, the `action_button.jsx` file only contains a placeholder generated by `{reactR}`. The reactstrap documentation provides a [boilerplate](https://reactstrap.github.io/components/buttons/), which we slightly modified, according to the `{reactR}` documentation:
```{r, echo=FALSE, results='asis'}
jsx_code <- "import { reactShinyInput } from 'reactR';
import { Button } from 'reactstrap';
function ActionButton() {
return (
<Button
color=\"primary\">
</Button>
);
}
reactShinyInput(
'.action_button',
'reactstrapTest.action_button',
ActionButton
);"
code_chunk_custom(jsx_code, "jsx")
```
As you can see, we need to import the `Button` component from `reactstrap` as well as
the `reactShinyInput` function from the `{reactR}` package. To generate our JS code, we recompile with `yarn run webpack`, document and reload the package functions:
```{r, eval=FALSE}
devtools::document()
devtools::load_all()
```
In the `./app.R` script, we have to tell Shiny we want to use Bootstrap 4 instead of Bootstrap 3, through the `bslib::bs_theme` function. Erase the existing code and replace it by the following:
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("demo-button", package = "reactstrapTest"))
```
As you can see Figure \@ref(fig:react-action-button-basic), the button label is not displayed nor its value.
This is because we missed to leverage the component arguments that are `configuration`, `value`, `setValue`, making the link between R and JS.
```{r react-action-button-basic, echo=FALSE, fig.cap='Work-in-progress action button with React.', out.width='100%'}
knitr::include_graphics("images/going-further/react-action-button-basic.png")
```
### Improve the JS logic
We modify the `action_button.jsx` code to add those three parameters to the `ActionButton` component:
```{r, echo=FALSE, results='asis'}
jsx_code <- "function ActionButton({ configuration, value, setValue }) {
return (
<Button
color={configuration.status}
onClick={() => setValue(value + 1)}>
{configuration.label}
</Button>
);
}"
code_chunk_custom(jsx_code, "jsx")
```
Remember that `configuration` is an R list and sent to JS as a JSON object with `reactR::createReactShinyInput()`. On the JS side, we access its properties with `configuration.<PROPERTY>`. `value` is the current button value, which is 0 when the app is started.
How do we update the button value upon click? Well, this is pretty straightforward. The `Button` element has an `onClick` [property](https://reactstrap.github.io/components/buttons/) inside which we can pass the `setValue` function and increment it by 1 (`setValue` is an internal hook, see section \@ref(react-hooks)).
In the below example, we update a button from the server side with `update_action_button()`:
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("demo-update-button", package = "reactstrapTest"))
```
Clicking on the first button should increment its value in the R console. You may play around
by changing the default color. After clicking on the second button, you should get the result shown Figure \@ref(fig:react-action-button).
```{r react-action-button, echo=FALSE, fig.cap='Fully working React-powered action button.', out.width='100%'}
knitr::include_graphics("images/going-further/react-action-button.png")
```
### Exercise 1
Based on the previous example and the `reactstrap` documentation, improve the action button component:
1. Add it a `size` style parameter.
2. Add it a `disabled` parameter.
3. Add it an `outline` style parameter.
### Technical considerations
Under the hood, the JS `reactShinyInput` function provides a wrapper to automatically __bind__ the input element. This is convenient as it allows you to solely focus on the component logic rather than binding it to the shiny system. It takes three parameters:
- The __element__ class, which is obtained from the R side by `createReactShinyInput()`.
- The __input binding__ name, which is useful to storing a reference in the `Shiny.InputBindings` registry. Recent versions of `{reactR}` use `<PACKAGE_NAME>.<INPUT_NAME>` as convention, which avoids conflicts between inputs belonging to two different packages.
- The React __component__ function.
- There is an optional fourth parameter allowing you to pass custom __options__ like
rate [policies](https://github.com/react-R/reactR/blob/7dccb68a0989cf642d4a5a3eb90b59d1ae773002/srcjs/input.js#L137).
Overall, [`reactShinyInput`](https://github.com/react-R/reactR/blob/7dccb68a0989cf642d4a5a3eb90b59d1ae773002/srcjs/input.js#L72) extends the `Shiny.InputBinding` class by providing extra methods like:
```{r, echo=FALSE, results='asis'}
js_code <- "getInputConfiguration(el) {
return $(el).data('configuration');
}
setInputConfiguration(el, configuration) {
$(el).data('configuration', configuration);
}"
code_chunk_custom(js_code, "js")
```
`getInputConfiguration` and `setInputConfiguration`, respectively, get and set the user-provided configuration, passed in the `createReactShinyInput()` R side function. Under the hood (in addition to the `{reactR}`, React, ReactTools HTML dependencies and any user-defined custom dependencies), `createReactShinyInput()` generates three tag elements:
- The first tag is the element placeholder containing the unique __id__. React will insert
the component inside this target with `ReactDOM.render`.
- The second tag is a script containing the __value__ passed as __JSON__.
- The second tag is a script containing the __configuration__, also passed as JSON.
```{r, eval=FALSE}
library(shiny)
reactR::createReactShinyInput(
inputId = "plop",
class = "myinput",
dependencies = htmltools::findDependencies(icon("bicycle")),
default = 0,
configuration = list(a = 1, b = "test"),
container = div
)
```
<!-- Manually formatted for pdf output -->
```{r, echo=FALSE, results='asis'}
tmp_code <- '#> <div id="plop" class="myinput"></div>
#> <script id="plop_value" type="application/json">0</script>
#> <script
#> id="plop_configuration"
#> type="application/json">{"a":1,"b":"test"}
#> </script>'
code_chunk_custom(tmp_code)
```
The configuration and values are processed in the __initialize__ method since it is called before the input is bound:
```{r, echo=FALSE, results='asis'}
js_code <- "// Within reactR's initialize method...
$(el).data('value', JSON.parse($(el).next().text()));
$(el).data(
'configuration',
JSON.parse($(el).next().next().text())
);"
code_chunk_custom(js_code, "js")
```
The configuration and values are stored in the corresponding data attributes. The most important part is the __render__ method, which creates the React element based upon its configuration and value and renders it in the DOM:
```{r, echo=FALSE, results='asis'}
js_code <- "// reactR's render method
render(el) {
const element = React.createElement(component, {
configuration: this.getInputConfiguration(el),
value: this.getValue(el),
setValue: this.setValue.bind(this, el),
el: el
});
ReactDOM.render(element, el);
}"
code_chunk_custom(js_code, "js")
```
The `render` method is called once inside `subscribe` and also each time the element is updated
with `receiveMessage`.
### Exercise 2 {#reactR-exercise-2}
1. Add an `icon` (from Font Awesome) parameter to the `ActionButton` component.
Hint: You might find it helpful to capture its HTML dependency with `htmltools::findDependencies(iconTag)` so as to properly render it. In HTML `icon("bicycle")` produces `<i class="fa fa-bicycle" role="presentation" aria-label="bicycle icon"></i>`. However, in React we want `<i className="fa fa-bicycle />`. Therefore, you will have to extract the icon class and send it to JS in the configuration list.
2. Implement the logic on the JS side. Hint: you may use the code in appendix \@ref(reactR-exercise-2-appendix).
3. Try your code inside a Shiny app.
### Add another input
#### Button group input
In this section, we design a radio input consisting of multiple buttons displayed side by side. The corresponding widget has a label and must show the currently selected value.
We initialized the input elements with:
```{r, eval=FALSE}
reactR::scaffoldReactShinyInput("button_group")
```
As shown previously, this creates `./srcjs/button_group.jsx` and `.R/button_group.R`.
The `button_group()` function has four parameters, the most critical being `choices`.
We expect the user to pass a vector like `names(mtcars)`, and we selected the first choice by default. We might add a `selected` parameter but leave this for the reader as a simple exercise. The function is defined below:
```{r, eval=FALSE}
button_group <- function(
inputId,
label,
choices,
status = "primary"
) {
reactR::createReactShinyInput(
inputId,
"button_group",
htmltools::htmlDependency(
name = "button_group-input",
version = "1.0.0",
src = "www/reactstrapTest",
package = "reactstrapTest",
script = "button_group.js"
),
default = choices[1],
configuration = list(
label = label,
choices = choices,
status = status
),
htmltools::tags$div
)
}
```
The expected `reactstrap` button group HTML structure is rather simple including a title, the list of button tags and the selected item in a paragraph:
```{r, echo=FALSE, results='asis'}
jsx_code <- "<div>
<h5>Radio Buttons</h5>
<ButtonGroup>
<Button
color=\"primary\"
onClick={...}
active={value === 1}>
One
</Button>
<Button
color=\"primary\"
onClick={...}
active={value === 2}>
Two
</Button>
// ... other buttons ...
</ButtonGroup>
<p>Selected: {value}</p>
</div>"
code_chunk_custom(jsx_code, "jsx")
```
Inside `./srcjs/button_group.jsx`, we first import the required function and components:
```{r, echo=FALSE, results='asis'}
jsx_code <- "import { reactShinyInput } from 'reactR';
import { Button, ButtonGroup } from 'reactstrap';"
code_chunk_custom(jsx_code, "jsx")
```
We then design the `ButtonGroupUI` JS function that will return our component. The critical step is to recover the user choices (`configuration.choices`) and store them in a variable. Then, we leverage the `map` feature (see section \@ref(react-map)) to iterate over each choice and programmatically create all buttons:
```{r, echo=FALSE, results='asis'}
jsx_code <- "function ButtonGroupUI({ configuration, value, setValue }) {
const choices = configuration.choices
// programmatically create buttons
const buttons = choices.map(
(choice) => <Button
key={choice}
color={configuration.status}
onClick={() => setValue(choice)}
active={value === choice}>
{choice}
</Button>
)
// ... other code"
code_chunk_custom(jsx_code, "jsx")
```
We finally return the whole component in a fragment `<>` to prevent creating extra `div`. The whole code is shown below:
```{r, echo=FALSE, results='asis'}
jsx_code <- "import { reactShinyInput } from 'reactR';
import { Button, ButtonGroup } from 'reactstrap';
function ButtonGroupUI({ configuration, value, setValue }) {
// ... create buttons ... //
return (
<>
<h5>{configuration.label}</h5>
<ButtonGroup>
{buttons}
</ButtonGroup>
<p>Selected: {value}</p>
</>
);
}"
code_chunk_custom(jsx_code, "jsx")
```
Now, we may test the newly created element in a Shiny app:
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("demo-button-group", package = "reactstrapTest"))
```
According to Figure \@ref(fig:react-button-group), there are rooms for improvements, but it is a good start!
```{r react-button-group, echo=FALSE, fig.cap='Fully working React powered button group (similar to the Shiny radio input).', out.width='100%'}
knitr::include_graphics("images/going-further/react-button-group.png")
```
#### Modularize JS code
Imagine if we had to repeat this for ten different elements. As we start to accumulate components, it is good practice to start modularizing our code. Inside the `./srcjs/action_button.jsx`, we wrap the `reactShinyInput` call into an `export` statement:
```{r, echo=FALSE, results='asis'}
jsx_code <- "// To add in ./srcjs/action_button.jsx
export default function initActionButton(){
reactShinyInput(
'.action_button',
'reactstrapTest.action_button',
ActionButton
);
}"
code_chunk_custom(jsx_code, "jsx")
```
We apply the same strategy in the `./srcjs/button_group.jsx` script:
```{r, echo=FALSE, results='asis'}
jsx_code <- "// To add in `./srcjs/button_group.jsx`
export default function initButtonGroup(){
reactShinyInput(
'.button_group',
'reactstrapTest.button_group',
ButtonGroupUI
);
}"
code_chunk_custom(jsx_code, "jsx")
```
We create a `main.jsx` file containing the necessary code to import and initialize our two components:
```{r, echo=FALSE, results='asis'}
jsx_code <- "import initActionButton from './action_button.jsx';
import initButtonGroup from './button_group.jsx';
initActionButton();
initButtonGroup();"
code_chunk_custom(jsx_code, "jsx")
```
We have to modify the `webpack.config.js` to change the entry point to `main.jsx`, whose output will be `main.js`:
```{r, echo=FALSE, results='asis'}
js_code <- "entry: [
path.join(__dirname, 'srcjs', 'main.jsx')
],
output: {
path: path.join(__dirname, 'inst/www/reactstrapTest'),
filename: 'main.js'
}"
code_chunk_custom(js_code, "js")
```
This means we have to update the HTML dependency on the R side, for instance in the `button_group.R`, we replace the existing dependency by the following:
```{r, eval=FALSE}
# ... button_group.R start
# ...
htmltools::htmlDependency(
name = "button_group-input",
version = "1.0.0",
src = "www/reactstrapTest",
package = "reactstrapTest",
script = "main.js"
)
# ...
# button_group.R end
```
We proceed similarly in the `action_button.R` script.
## Further resources
`{shiny.fluent}` [@R-shiny.fluent] leverages `{shiny.react}` [@R-shiny.react], which is another [alternative](https://appsilon.github.io/shiny.react/index.html) to bring React to Shiny.