Skip to content

Commit 1e45181

Browse files
authored
Merge pull request #96 from reason-association/new-react-docs-only
New react docs (only content)
2 parents e98d70b + 7fc4e19 commit 1e45181

27 files changed

+3821
-14
lines changed

data/sidebar_react_latest.json

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"Overview": [
3+
"introduction",
4+
"installation"
5+
],
6+
"Main Concepts": [
7+
"elements-and-jsx",
8+
"rendering-elements",
9+
"components-and-props",
10+
"arrays-and-keys",
11+
"refs-and-the-dom",
12+
"context"
13+
],
14+
"Hooks & State Management": [
15+
"hooks-overview",
16+
"hooks-effect",
17+
"hooks-state",
18+
"hooks-reducer",
19+
"hooks-context",
20+
"hooks-ref",
21+
"hooks-custom"
22+
],
23+
"Guides": [
24+
"beyond-jsx",
25+
"forwarding-refs"
26+
]
27+
}

pages/docs/manual/latest/api/js.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ or the JavaScript
88
[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
99
classes.
1010

11-
It is meant as a zero-abstraction interop layer and directly exposes JavaScript functions as they are. If you can find your API in this module, prefer this over an equivalent Belt helper. For example, prefer [Js.Array2](js/array2) over [Belt.Array](belt/array)
11+
It is meant as a zero-abstraction interop layer and directly exposes JavaScript functions as they are. If you can find your API in this module, prefer this over an equivalent Belt helper. For example, prefer [Js.Array2](js/array-2) over [Belt.Array](belt/array)
1212

1313
## Argument Order
1414

pages/docs/manual/v8.0.0/api/js.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ or the JavaScript
88
[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
99
classes.
1010

11-
It is meant as a zero-abstraction interop layer and directly exposes JavaScript functions as they are. If you can find your API in this module, prefer this over an equivalent Belt helper. For example, prefer [Js.Array2](js/array2) over [Belt.Array](belt/array)
11+
It is meant as a zero-abstraction interop layer and directly exposes JavaScript functions as they are. If you can find your API in this module, prefer this over an equivalent Belt helper. For example, prefer [Js.Array2](js/array-2) over [Belt.Array](belt/array)
1212

1313
## Argument Order
1414

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
---
2+
title: Arrays and Keys
3+
description: "Rendering arrays and handling keys in ReScript and React"
4+
canonical: "/docs/react/latest/arrays-and-keys"
5+
---
6+
7+
# Arrays and Keys
8+
9+
<Intro>
10+
11+
Whenever we are transforming data into an array of elements and put it in our React tree, we need to make sure to give every element an unique identifier to help React distinguish elements for each render. This page will explain the `key` attribute and how to apply it whenever we need to map data to `React.element`s.
12+
13+
</Intro>
14+
15+
## Keys & Rendering Arrays
16+
17+
Keys help React identify which elements have been changed, added, or removed throughout each render. Keys should be given to elements inside the array to give the elements a stable identity:
18+
19+
```res
20+
let numbers = [1, 2, 3, 4, 5];
21+
22+
let items = Belt.Array.map(numbers, (number) => {
23+
<li key={Belt.Int.toString(number)}> {React.int(number)} </li>
24+
})
25+
```
26+
27+
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:
28+
29+
```res
30+
type todo = {id: string, text: string}
31+
32+
let todos = [
33+
{id: "todo1", text: "Todo 1"},
34+
{id: "todo2", text: "Todo 2"}
35+
]
36+
37+
let items = Belt.Array.map(todos, todo => {
38+
<li key={todo.id}> {React.string(todo.text)} </li>
39+
})
40+
```
41+
42+
If you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
43+
44+
```res {2,3}
45+
let items = Belt.Array.mapWithIndex(todos, (todo, i) => {
46+
// Only do this if items have no stable id
47+
<li key={i}>
48+
{todo.text}
49+
</li>
50+
});
51+
```
52+
53+
### Keys Must Only Be Unique Among Siblings
54+
55+
Keys used within arrays should be unique among their siblings. However they don’t need to be globally unique. We can use the same keys when we produce two different arrays:
56+
57+
```res {6,10,17,18,25,27}
58+
type post = {id: string, title: string, content: string}
59+
60+
module Blog = {
61+
@react.component
62+
let make = (~posts: array<post>) => {
63+
let sidebar =
64+
<ul>
65+
{
66+
Belt.Array.map(posts, (post) => {
67+
<li key={post.id}>
68+
{React.string(post.title)}
69+
</li>
70+
})->React.array
71+
}
72+
</ul>
73+
74+
let content = Belt.Array.map(posts, (post) => {
75+
<div key={post.id}>
76+
<h3>{React.string(post.title)}</h3>
77+
<p>{React.string(post.content)}</p>
78+
</div>
79+
});
80+
81+
<div>
82+
{sidebar}
83+
<hr />
84+
{React.array(content)}
85+
</div>
86+
}
87+
}
88+
89+
let posts = [
90+
{id: "1", title: "Hello World", content: "Welcome to learning ReScript & React!"},
91+
{id: "2", title: "Installation", content: "You can install reason-react from npm."}
92+
]
93+
94+
let blog = <Blog posts/>
95+
```
96+
97+
98+
## Rendering `list` Values
99+
100+
In case you ever want to render a `list` of items, you can do something like this:
101+
102+
```res
103+
type todo = {id: string, text: string}
104+
let todoList = list{
105+
{id: "todo1", text: "Todo 1"},
106+
{id: "todo2", text: "Todo 2"}
107+
}
108+
109+
let items =
110+
todoList
111+
->Belt.List.toArray
112+
->Belt.List.map((todo) => {
113+
<li key={todo.id}>
114+
{React.string(todo.text)}
115+
</li>
116+
})
117+
118+
<div> {React.array(items)} </div>
119+
```
120+
121+
We use `Belt.List.toArray` to convert our list to an array before creating our `array<React.element>`. Please note that using `list` has performance impact due to extra conversion costs.
122+
123+
In 99% you'll want to use arrays (seamless interop, faster JS code), but in some cases it might make sense to use a `list` to leverage advanced pattern matching features etc.
124+
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
---
2+
title: Beyond JSX
3+
description: "Details on how to use ReScript and React without JSX"
4+
canonical: "/docs/react/latest/beyond-jsx"
5+
---
6+
7+
# Beyond JSX
8+
9+
<Intro>
10+
11+
JSX is a syntax sugar that allows us to use React components in an HTML like manner. A component needs to adhere to certain interface conventions, otherwise it can't be used in JSX. This section will go into detail on how the JSX transformation works and what React APIs are used underneath.
12+
13+
</Intro>
14+
15+
**Note:** This section requires knowledge about the low level apis for [creating elements](./elements-and-jsx#creating-elements-from-component-functions), such as `React.createElement` or `ReactDOMRe.createDOMElementVariadic`.
16+
17+
> **Note:** This page assumes your `bsconfig.json` to be set to `"reason": { "react-jsx": 3 }` to apply the right JSX transformations.
18+
19+
## Component Types
20+
21+
A plain React component is defined as a `('props) => React.element` function. You can also express a component more efficiently with our shorthand type `React.component('props)`.
22+
23+
Here are some examples on how to define your own component types (often useful when interoping with existing JS code, or passing around components):
24+
25+
```res
26+
// Plain function type
27+
type friendComp =
28+
({"name": string, "online": bool}) => React.element;
29+
30+
// Equivalent to
31+
// ({"padding": string, "children": React.element}) => React.element
32+
type containerComp =
33+
React.component({
34+
"padding": string,
35+
"children": React.element
36+
});
37+
```
38+
The types above are pretty low level (basically the JS representation of a React component), but since ReScript React has its own ways of defining React components in a more language specific way, let's have a closer look on the anatomy of such a construct.
39+
40+
## JSX Component Interface
41+
42+
A ReScript React component needs to be a (sub-)module with a `make` and `makeProps` function to be usable in JSX. To make things easier, we provide a `@react.component` decorator to create those functions for you:
43+
44+
<CodeTab labels={["Decorated", "Expanded"]}>
45+
46+
```res
47+
module Friend = {
48+
@react.component
49+
let make = (~name: string, ~children) => {
50+
<div>
51+
{React.string(name)}
52+
children
53+
</div>
54+
}
55+
}
56+
```
57+
```res
58+
module Friend = {
59+
[@bs.obj]
60+
external makeProps: (
61+
~name: string,
62+
~children: 'children,
63+
~key: string=?,
64+
unit) => {. "name": string, "children": 'children'} = "";
65+
66+
let make = (props: {. "name": string, "children": 'children}) => {
67+
// React element creation from the original make function
68+
}
69+
}
70+
```
71+
72+
</CodeTab>
73+
74+
In the expanded output:
75+
76+
- `makeProps`: A function that receives multiple labeled arguments (according to prop names) and returns the value that is consumed by make(props)
77+
- `make`: A converted `make` function that complies to the component interface `(props) => React.element`
78+
79+
**Note:** The `makeProps` function will also always contain a `~key` prop.
80+
81+
### Special Case React.forwardRef
82+
83+
The `@react.component` decorator also works for `React.forwardRef` calls:
84+
85+
86+
<CodeTab labels={["Decorated", "Expanded"]}>
87+
88+
```res
89+
module FancyInput = {
90+
@react.component
91+
let make = React.forwardRef((~className=?, ~children, ref_) =>
92+
<div>
93+
// use ref_ here
94+
</div>
95+
)
96+
}
97+
```
98+
99+
```res
100+
// Simplified Output
101+
module FancyInput = {
102+
@bs.obj
103+
external makeProps: (
104+
~className: 'className=?,
105+
~children: 'children,
106+
~key: string=?,
107+
~ref: 'ref=?,
108+
unit,
109+
) => {"className": option<'className>, "children": 'children} = ""
110+
111+
let make =
112+
(~className=?, ~children) => ref_ => ReactDOMRe.createDOMElementVariadic("div", [])
113+
114+
let make = React.forwardRef(
115+
(props: {"className": option<'className>, "children": 'children}, ref_,) => {
116+
make(
117+
~className=props["className"],
118+
~children=props["children"],
119+
ref_)
120+
})
121+
}
122+
```
123+
124+
</CodeTab>
125+
126+
As shown in the expanded output above, our decorator desugars the function passed to `React.forwardRef` in the same manner as a typical component `make` function. It also creates a `makeProps` function with a `ref` prop, so we can use it in our JSX call (`<FancyInput ref=.../>`).
127+
128+
So now that we know how the ReScript React component transformation works, let's have a look on how ReScript transforms our JSX constructs.
129+
130+
## JSX Under the Hood
131+
132+
Whenever we are using JSX with a custom component ("capitalized JSX"), we are actually using `React.createElement` to create a new element. Here is an example of a React component without children:
133+
134+
<CodeTab labels={["JSX", "Without JSX"]}>
135+
136+
```res
137+
<Friend name="Fred" age=1 />
138+
```
139+
```res
140+
React.createElement(Friend.make, Friend.makeProps(~name="Fred", ~age=1, ()))
141+
```
142+
```js
143+
React.createElement(Playground$Friend, { name: "Fred", age: 20 });
144+
```
145+
146+
</CodeTab>
147+
148+
As you can see, it uses `Friend.make` and `Friend.makeProps` to call the `React.createElement` API. In case you are providing children, it will use `React.createElementVariadic` instead (which is just a different binding for `React.createElement`):
149+
150+
<CodeTab labels={["JSX", "Without JSX", "JS Output"]}>
151+
152+
```res
153+
<Container width=200>
154+
{React.string("Hello")}
155+
{React.string("World")}
156+
</Container>
157+
```
158+
159+
```res
160+
React.createElementVariadic(
161+
Container.make,
162+
Container.makeProps(~width=200, ~children=React.null, ()),
163+
[{React.string("Hello")}, {React.string("World")}],
164+
)
165+
```
166+
167+
```js
168+
React.createElement(Container, { width: 200, children: null }, "Hello", "World");
169+
```
170+
171+
</CodeTab>
172+
173+
Note that the `~children=React.null` prop has no relevance since React will only care about the children array passed as a third argument.
174+
175+
176+
### Dom Elements
177+
178+
"Uncapitalized JSX" expressions are treated as DOM elements and will be converted to `ReactDOMRe.createDOMElementVariadic` calls:
179+
180+
<CodeTab labels={["JSX", "Without JSX", "JS Output"]}>
181+
182+
```res
183+
<div title="test"/>
184+
```
185+
186+
```res
187+
ReactDOMRe.createDOMElementVariadic("div", ~props=ReactDOMRe.domProps(~title="test", ()), [])
188+
```
189+
190+
```js
191+
React.createElement("div", { title: "test" });
192+
```
193+
194+
</CodeTab>
195+
196+
The same goes for uncapitalized JSX with children:
197+
198+
<CodeTab labels={["JSX", "Without JSX", "JS Output"]}>
199+
200+
```res
201+
<div title="test">
202+
<span/>
203+
</div>
204+
```
205+
206+
```res
207+
ReactDOMRe.createDOMElementVariadic(
208+
"div",
209+
~props=ReactDOMRe.domProps(~title="test", ()),
210+
[ReactDOMRe.createDOMElementVariadic("span", [])],
211+
)
212+
```
213+
214+
```js
215+
React.createElement("div", { title: "test" }, React.createElement("span", undefined));
216+
```
217+
218+
</CodeTab>

0 commit comments

Comments
 (0)