<Show>
Edit this pageThe <Show>
component is used for conditionally rendering UI elements.
It takes a when
prop that defines the condition for rendering.
When the when
prop is truthy, the children of the <Show>
component are displayed.
Additionally, an optional fallback
prop can be provided to specify an element that is shown when the condition is falsy.
import { createSignal, Show } from "solid-js";
function Example() { const [value, setValue] = createSignal(true); return ( <div> <button onClick={() => setValue((prev) => !prev)}>Toggle Show</button> <Show when={value()} fallback={<div>Fallback Element</div>}> <div>Child Element</div> </Show> </div> );}
Keyed rendering
When the keyed
prop is set to true
, the children of the <Show>
component are re-rendered every time the when
prop changes.
It's important to note that in this case, even if the reference of the when
prop changes, the children will still re-render.
import { createSignal, Show } from "solid-js";
function KeyedExample() { const [user, setUser] = createSignal({ name: "John Wick" });
function update() { // This operation changes the reference of the user object. setUser({ ...user() }); }
return ( <div> <button onClick={update}>Update</button> <Show when={user()} keyed> <p>Name: {user().name}</p> {/* Updates shown with each click */} <p>Last updated: {Date.now()}</p> </Show> </div> );}
Render function
The <Show>
component can also accept a render function as its child.
In this case, the first argument of the render function is an accessor to the when
prop.
However, when the keyed
prop is set to true
, the argument is the when
prop itself instead of an accessor.
The render function is treated like a separate component.
A key point to understand is that the render function is wrapped in untrack
.
As a result, any changes to signals accessed directly within the render function will not trigger updates.
For example, in the following code, clicking the increment button does not update the count value displayed on the screen because the count
signal is not tracked.
import { createSignal, Show } from "solid-js";
function RenderFunctionExample() { const [count, setCount] = createSignal(0); return ( <div> <button onClick={() => setCount((c) => c + 1)}>Increment</button> {/* This does not update because the count signal is not being tracked. */} <Show when={count()}>{(c) => count()}</Show> {/* This will update because the outer JSX element creates a tracking scope. */} <Show when={count()}>{(c) => <>{count()}</>}</Show> </div> );}
Props
Name | Type | Description |
---|---|---|
when | T | undefined | null | false | The condition value. |
keyed | boolean | Whether to key the block to the value of when. |
fallback | JSX.Element | The fallback to render when the when prop is falsy. |