Skip to content

Input

Description

Type-safe and/or controlled input component.

Controlled components are well known in the React community but are not available in Solid.js as it does not work with a virtual DOM.

While it is possible to emulate the behaviour of a controlled component with the 'onInput' listener, it is not really possible and there are many cases where the component is no longer controlled.

With the Input component it is possible to control its value and also ensure TypeScript typing based on the field type.

Import

import { Input } from "dreamkit";

Definition

import type { JSXElement, ComponentProps } from "solid-js";
type OverrideProps<T, U> = Omit<T, keyof U> & U;
declare function Input(
props: OverrideProps<
ComponentProps<"input">,
{
type: string;
value?: any | (() => any);
defaultValue?: any;
onChange?: (value: any) => void;
onNativeChange?: ComponentProps<"input">["onChange"];
}
>,
): JSXElement;

Examples

Controlled text

import { $route, Input } from "dreamkit";
import { createSignal } from "solid-js";
export default $route.path("/").create(() => {
const [name, setName] = createSignal("");
return (
<>
<p>value: {name()}</p>
<Input value={name} onChange={(value) => setName(value.toUpperCase())} />
</>
);
});

Controlled number

import { $route, Input } from "dreamkit";
import { createEffect, createSignal } from "solid-js";
export default $route.path("/").create(() => {
const [number, setNumber] = createSignal<number | null>(0);
createEffect(() => console.log("number", number()));
return (
<>
<p>value: {JSON.stringify(number())}</p>
<Input
type="number"
value={number}
onChange={(value) => {
if (value === null || value < 100) setNumber(value);
}}
/>
</>
);
});

Controlled checkbox

import { $route, Input } from "dreamkit";
import { createSignal } from "solid-js";
export default $route.path("/").create(() => {
const [bool, setBool] = createSignal(false);
return (
<>
<p>value: {JSON.stringify(bool())}</p>
<Input type="checkbox" value={bool} onChange={setBool} />
</>
);
});

Controlled file

import { $route, Input } from "dreamkit";
import { createEffect, createSignal } from "solid-js";
export default $route.path("/").create(() => {
const [file, setFile] = createSignal<File | null>(new File([], "file.txt"));
createEffect(() => console.log("file", file()));
return (
<>
<p>value: {file()?.name}</p>
<Input type="file" value={file} onChange={setFile} />
</>
);
});

Uncontrolled text

import { $route, Input } from "dreamkit";
export default $route.path("/").create(() => {
return (
<Input
defaultValue="example"
onChange={(value) => console.log("value", value)}
/>
);
});