Sayedur Rahman
Sayedur Rahman

Reputation: 13

The type ''a list' is not compatible with the type 'ReactElement'

I am trying generate multiple div from a list of strings. Generating single div with string is working fine

div []
    [ "mytext" |> str ]

But following code showing an error when trying to generate by a list of string

"The type ''a list' is not compatible with the type 'ReactElement'"

  div []
    [
      myList
        |> List.map(fun f ->
            div[]
            [f |> str])]
    ]

Upvotes: 1

Views: 394

Answers (1)

DaveShaw
DaveShaw

Reputation: 52818

The problem is the extra [] after your first div.

In the following: div [] [ "hello" |> str ] you have 2 lists. The first is an empty list of properties, the second is a list of child elements - with one child element "hello" > str.

In your second example you have the same 2 lists, the first still empty, the second contains another list, so you have a list with a list of react elements.

You need to just pass a list of react elements on their own.

Consider the following:

let words = ["Hello"; "World"; ]

let mapWords = //ReactElement list
    words |> List.map (fun w -> div[] [w |> str])

div [] [ mapWords ]
|> mountById "elmish-app" //added for fable REPL

[ mapWords ] is a list with a list.

What you do when you already have a list of react elements is just pass them as the second parameter to div:

div [] mapWords
|> mountById "elmish-app"

Or if you don't feel like a separate function:

div [] (words |> List.map (fun w -> div[] [w |> str]))

You need the extra parentheses around the expression, so F# knows it is all one expression, which is why I generally prefer to use smaller functions, and they also help keep it cleaner.

Examples in the Fable Repl here.

Upvotes: 2

Related Questions