You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Interestingly, it doesn't matter if you are passing just one element, or several, React will always collapse its children to a single `React.element`.
195
+
196
+
It is also possible to redefine the `children` type as well. Here are some examples:
197
+
198
+
**Component with a mandatory `string` as children:**
199
+
200
+
```res
201
+
module StringChildren = {
202
+
@react.component
203
+
let make = (~children: string) => {
204
+
<div>
205
+
{React.string(children)}
206
+
</div>
207
+
}
208
+
}
209
+
210
+
<StringChildren> "My Child" </StringChildren>
211
+
212
+
// This will cause a type check error
213
+
<StringChildren/>
214
+
```
215
+
216
+
**Component with an optional `React.element` as children:**
217
+
218
+
```res
219
+
module OptionalChildren = {
220
+
@react.component
221
+
let make = (~children: option<React.element>=?) => {
222
+
<div>
223
+
{switch children {
224
+
| Some(element) => element
225
+
| None => React.string("No children provided")
226
+
}}
227
+
</div>
228
+
}
229
+
}
230
+
231
+
<div>
232
+
<OptionalChildren />
233
+
<OptionalChildren> <div /> </OptionalChildren>
234
+
</div>
235
+
```
236
+
237
+
**Component that doesn't allow children at all:**
238
+
239
+
```res
240
+
module NoChildren = {
241
+
@react.component
242
+
let make = () => {
243
+
<div>
244
+
{React.string("I don't accept any children params")}
245
+
</div>
246
+
}
247
+
}
248
+
249
+
// The compiler will raise a type error here
250
+
<NoChildren> <div/> </NoChildren>
251
+
```
252
+
253
+
Children props are really tempting to be abused as a way to model hierarchies, e.g. `<List> <ListHeader/> <Item/> </List>` (`List` should only allow `Item` / `ListHeader` elements), but this kind of constraint is hard to enforce because all components end up being `React.element`, so it would require notorious runtime checking within `List` to verify that all children are in fact of type `Item` or `ListHeader`.
254
+
255
+
The best way to approach this kind of issue is by using props instead of children, e.g. `<List header="..." items=[{id: "...", text: "..."}]/>`. This way it's easy to type check the constraints, and also spares us many hours debugging and remembering component constraints.
256
+
257
+
**The best use-case for `children` is to pass down `React.element`s, no matter what kind of elements they are!**
258
+
259
+
260
+
93
261
### Type Inference
94
262
95
263
The ReScript type system excels at computing the actual prop types through usage. We recommend to explicitly type your props (especially for exported components) to help your coworkers understand the types. For simple cases or experimentation, it's still fine to omit them:
0 commit comments