Capitalised JSX Component?

In Rescript JSX Documentation, it is suggested one can perform <MyComponent>...myChild</MyComponent>

I am not able to find how one can initialise <MyComponent> to fit list<React.element> as its children.

To assign the argument ~children to the returned element, the problem of assigning a list to ~children occurs once again but it gives error.

In short, can anyone provide me an example how <MyComponent>...myChild</MyComponent> can be done? (myChild is a list of React.element)

Thank you very much in advance

1 Like

Not sure what you are trying to achieve, but in idiomatic ReScript / React, you’d type children as a React.element (instead of list<React.element>), since this is what children are (even if there are multiple children).

Example:

module MyComponent = {
  @react.component
  let make = (~children: React.element) => {
    <div> children </div>
  }
}

module Test = {
  @react.component
  let make = () => {
     <MyComponent>
       <div> {React.string("child 1")} </div>
       <div> {React.string("child 2")} </div>
    </MyComponent>
  }
}

Let’s assume you’d still want to pass your children as a list<React.element>, you’d need to do something like this:

module MyComponent = {
  @react.component
  let make = (~children: list<React.element>) => {
    <div> {Belt.List.toArray(children)->React.array} </div>
  }
}

module Test = {
  @react.component
  let make = () => {
    let children = list{
      <div> {React.string("child 1")} </div>,
      <div> {React.string("child 2")} </div>,
    }
    <MyComponent> children </MyComponent>
  }
}

I personally would recommend to never use list for this particular use-case, since it will always introduce extra runtime overhead when converting lists to arrays.

2 Likes

Thanks! The second snippet works!

The idea of passing list<React.element> came from how JSX elements are desugared to:

@JSX MyComponent.createElement(~name="ReScript", ~children=list{}, ())

My use case is similar to having an array of React.element in vanilla React from an API call.

May I know is there a place where I can find all the Rescript types from React? (i.e. React.array).

Since you enabled your JSX config in bsconfig.json, the representation you mentioned above will be converted to the React-specific React.createElement(comp, props) instead. You would have been correct with your assumption if your JSX setting would have been disabled.

Or to phrase it differently, when using ReScript w/ React, you always have two transformations in the JSX syntax. 1) From JSX to annotated @JSX MyComponent.createElement(...), which gets transformed by our builtin react-jsx-ppx (v3).

Right now, the official docs for rendering all the different primitive values are here

3 Likes