Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

Rendering Recursive React Components

$
0
0

Hello! I have some questions about rendering recursive react components.

See this small example:

type rec item<'a> = {
  name: string,
  nested: option<item<'a>>,
}

module Item = {
  @react.component
  let rec make = (~item: item<'a>) => {
    <li className="item">
      <div className="name"> {React.string(item.name)} </div>
      {switch item.nested {
      | Some(nested) => <Item item=nested />
      | None => React.null
      }}
    </li>
  }
}

@react.component
let make = (~items: array<item<'a>>) => {
  <ul className="generic-list">
    {items->Array.map(item => <Item key={item.name} item />)->React.array}
  </ul>
}

Playground link

Results in

[E] Line 12, column 25:
The module or file Item can't be found.
  - If it's a third-party dependency:
    - Did you add it to the "bs-dependencies" or "bs-dev-dependencies" in bsconfig.json?
  - Did you include the file's directory to the "sources" in bsconfig.json?

I tried a few different things like making the recursive make function and using it, making the module recursive but then it asks me for a type signature and when I write it down I’m probably doing it wrong and I get different type errors that I don’t know how to solve.

In the end I managed to solve it by directly using React.createElement. But it’s kind of ugly, so I’m wondering is there a better way to do this?

module Item = {
  @react.component
  let rec make = (~item: item<'a>) => {
    <li className="item">
      <div className="name"> {React.string(item.name)} </div>
      {switch item.nested {
      | Some(nested) => React.createElement(make, {item: nested})
      | None => React.null
      }}
    </li>
  }
}

Viewing all articles
Browse latest Browse all 2592

Trending Articles