Conditional rendering
Edit this pageConditional rendering is the process of displaying different UI elements based on certain conditions. This is a common pattern in UI development, and is often used to show or hide elements based on user input, data, or other conditions.
Solid offers dedicated components to handle conditional rendering in a more straightforward and readable way.
Show
<Show>
renders its children when a condition is evaluated to be true.
Similar to the ternary operator in JavaScript, it uses control logic flow within JSX to determine what to render.
<Show>
has a when
property that is used to determine whether or not to render its children.
When there is a change in the state or props it depends on, this property is re-evaluated.
This property can be a boolean value, or a function that returns a boolean value.
<Show>
has the fallback
property that can be used to specify the content to be rendered when the condition evaluates to false.
This property can return a JSX element.
If there are multiple conditions that need to be handled, <Show>
can be nested to handle each condition.
Switch and Match
When there are multiple conditions that need to be handled, it can be difficult to manage the logic flow with nested <Show>
components.
Solid has the <Switch>
and <Match>
components for this purpose.
Similar to JavaScript's switch/case structure, <Switch>
wraps multiple <Match>
components so that each condition is evaluated in sequence.
The first <Match>
component that evaluates to true will have its children rendered, and the rest will be ignored.
Similar to <Show>
, each <Match>
component has a when
property that is used to determine whether or not to render its children.
An optional fallback
property can also be passed to <Switch>
to specify the content be rendered when none of the <Match>
components evaluate to true.