trevorsg
trevorsg
SSolidJS
Created by trevorsg on 7/6/2023 in #support
Brand new going through the tutorial. Unsure of the purpose of the <Dynamic> component.
I feel like I'm missing something obvious. The tutorial page for the <Dynamic> component introduces it as a more compact alternative to a bunch of <Show> or <Switch> components. The "Solution" to the code wants me to replace a <Switch> with <Dynamic component={options[selected()]} />. But why do I even need <Dynamic>? See the full code below.
import { render, Dynamic } from "solid-js/web";
import { createSignal, For } from "solid-js";

const RedThing = () => <strong style="color: red">Red Thing</strong>;
const GreenThing = () => <strong style="color: green">Green Thing</strong>;
const BlueThing = () => <strong style="color: blue">Blue Thing</strong>;

const options = {
red: RedThing,
green: GreenThing,
blue: BlueThing
}

function App() {
const [selected, setSelected] = createSignal("red");

return (
<>
<select value={selected()} onInput={e => setSelected(e.currentTarget.value)}>
<For each={Object.keys(options)}>{
color => <option value={color}>{color}</option>
}</For>
</select>

{ /* The suggested solution */ }
<Dynamic component={options[selected()]} />

{ /* But why not just use this? It seems to have the exact same output */ }
{ options[selected()] }
</>
);
}

render(() => <App />, document.getElementById("app"));
import { render, Dynamic } from "solid-js/web";
import { createSignal, For } from "solid-js";

const RedThing = () => <strong style="color: red">Red Thing</strong>;
const GreenThing = () => <strong style="color: green">Green Thing</strong>;
const BlueThing = () => <strong style="color: blue">Blue Thing</strong>;

const options = {
red: RedThing,
green: GreenThing,
blue: BlueThing
}

function App() {
const [selected, setSelected] = createSignal("red");

return (
<>
<select value={selected()} onInput={e => setSelected(e.currentTarget.value)}>
<For each={Object.keys(options)}>{
color => <option value={color}>{color}</option>
}</For>
</select>

{ /* The suggested solution */ }
<Dynamic component={options[selected()]} />

{ /* But why not just use this? It seems to have the exact same output */ }
{ options[selected()] }
</>
);
}

render(() => <App />, document.getElementById("app"));
Is it just a helper so it's easier to pass props? I come from React, so I would typically build a props object and spread it, i.e.
const ColoredThing = options[selected];
const propsForThing = { prop1: 42, prop2: 69 };
return // ...
<ColoredThing {...propsForThing} /> // ...
const ColoredThing = options[selected];
const propsForThing = { prop1: 42, prop2: 69 };
return // ...
<ColoredThing {...propsForThing} /> // ...
9 replies