Search code examples
reasonreason-react

Printing lists with unknown length


I've got a list(string) with an unknown length which I would like to render in my ReasonReact component. I've read that there is no built-in support for printing complex data structures. But how would one go about rendering a list in its component in a pure functional way without using Javascript? I've found a snippet that achieves this using recursion on pattern matching. I presume there must be an easier way as this seems like a rather often-used operation.

The Javascript equivalent of what I'm trying to achieve is Array.toString().


Solution

  • If I understand you correctly, there are two steps you want accomplished:

    1. To create a string out of the list(string), preferably formatted in the same way Array.toString does, i.e. comma-separated without surrounding square brackets, and without using any JavaScript-specific APIs.
    2. To render the string as a ReasonReact component.

    Step 1: String conversion

    This can be done using String.concat:

    let myList = ["a", "b", "c"];
    let myString = String.concat(", ", myList);
    

    which will return "a, b, c"

    Step 2: Render as ReasonReact component

    Rendering strings in ReasonReact are done using ReasonReact.string. Here's a complete, runnable example of a component taking a prop items of type list(string) and rendering it in a <span> element.

    module ListRenderer = {
      let component = ReasonReact.statelessComponent("ListRenderer");
      let make = (~items, _children) => {
        ...component,
        render: _self =>
          <span> {ReasonReact.string(String.concat(", ", items))} </span>
      };
    };
    
    ReactDOMRe.renderToElementWithId(<ListRenderer items=["a", "b", "c"] />, "preview");
    

    Playground link