Owl
Owl

Reputation: 6853

Array of JSX Elements not rendering on second loop

I have a Solid.js code that looks like this:

import { render, For } from "solid-js/web";

const Text = () => <div style="color: red">Example</div>;

const App = () => {
  const elements = [<Text/>, <Text/>, <Text/>];

  return (
    <div>
      <div>First For Each</div>
      <For each={elements}>{(E) => E}</For>

      <div>Second For Each</div>
      <For each={elements}>{(E) => E}</For>
    </div>
  );
}

render(() => <App />, document.getElementById("app")!);

But for some reason Solid.js only renders the second <For>:

first

And when I change the elements to:

const elements = [() => <Text/>, () => <Text/>, () => <Text/>];

it renders twice (also works fine if I change the elements value to primitive value like int or string. Can someone explain to me why Solid.js behaves this way?

Playground Example

Upvotes: 1

Views: 796

Answers (1)

thetarnav
thetarnav

Reputation: 898

Writing <Text/> executes the Text component which returns an actual DOM node. And dom nodes can be inserted only in one place in the DOM.

The attempt with wrapping the component execution with functions works because you'll get a different element instance every time you execute that function. You're basically creating an array of components vs an array of HTML elements.

Here is a similar Github issue: https://github.com/solidjs/solid/issues/899

Upvotes: 3

Related Questions