react-input-material
v0.0.858
Published
Reusable material design based input field with support for (richt-)text, code, selections, numbers, dates and so on.
Maintainers
Readme
Project Status
Use case
Form inputs for React in Material Design, built on RMWC. One "TextInput" component covers plain and multiline text, numbers, currencies, dates and times, selections with search and suggestions, a code editor and a rich text editor. Further components handle checkboxes, files, time intervals and lists of inputs. All of them share the same model: declare constraints like "required", "minimum" or "pattern" and the component validates, shows messages and reports value and validation state to you.
Features included:
- "TextInput": Text, numbers, currencies, dates, times, selections, code and rich text.
- "Checkbox", "FileInput" with preview, "Interval" for time ranges and "Inputs" for dynamic lists of any input.
- Declarative validation with customizable messages.
- Controlled and uncontrolled usage.
- Editors are loaded lazily on first use.
- Theming, tooltips and Playwright harnesses for end-to-end tests.
Installation
Install the package together with the libraries it builds on:
npm install \
react-input-material \
clientnode core-js prop-types react react-dom \
react-generic-animate react-generic-dummy react-generic-tools \
react-transition-group react-useanimations blob-util spark-md5 \
material-icons \
@rmwc/card @rmwc/checkbox @rmwc/circular-progress @rmwc/icon \
@rmwc/icon-button @rmwc/menu @rmwc/select @rmwc/textfield @rmwc/theme \
@rmwc/typographyInclude the styles and the icon font once, e.g. in your main stylesheet:
@import "material-icons/iconfont/material-icons.css";
@import "react-input-material/index.css";Then use the components:
import {
Checkbox, FileInput, Inputs, Interval, TextInput
} from 'react-input-material'Build variants
Instead of installing all libraries above you can use a variant which already contains them. Only "react", "react-dom" and the icon font "material-icons" have to be installed then. Each variant offers the same paths as the default one below its own prefix, e.g. "react-input-material/bundle/components/TextInput" or "react-input-material/bundle/index.css":
- "react-input-material/bundle": Everything included, also both editors.
- "react-input-material/bundle/minimal": Everything included except the editors, tooltips and animated icons, so it is much smaller.
- "react-input-material/minimal": Like the default variant, but without editors, tooltips and animated icons and their libraries.
Optional features
Some features need additional packages:
- Tooltips: "@rmwc/tooltip".
- Code editor: "@codemirror/autocomplete", "@codemirror/commands", "@codemirror/lang-css", "@codemirror/lang-javascript", "@codemirror/language", "@codemirror/lint", "@codemirror/search", "@codemirror/state" and "@codemirror/view".
- Rich text editor: "@tiptap/core", "@tiptap/extensions", "@tiptap/react" and "@tiptap/starter-kit".
If you do not install the packages of a feature, point them to the included empty shim so that your bundler can still resolve them. The feature is then left out. Example for the rich text editor with webpack, the code editor and tooltip packages work the same way:
export default {
resolve: {
alias: {
'@tiptap/core$': 'react-input-material/shims/optionals',
'@tiptap/extensions$': 'react-input-material/shims/optionals',
'@tiptap/react$': 'react-input-material/shims/optionals',
'@tiptap/starter-kit$': 'react-generic-dummy'
}
}
}Basics
Each input reports its state via callbacks. "onChangeValue" receives the new value, "onChange" receives all current properties including "value", "valid", "invalid", "dirty" and "touched":
Simple uncontrolled input
const Application = () =>
<TextInput<string>
name="simpleInput"
onChange={({value, invalid}) => {
console.log('Set value', value)
if (invalid)
console.log('Value is invalid!')
}}
/>Simple controlled input
Pass "value" to control the input yourself. Use "initialValue" or "default" to only set a starting value:
const Application = () => {
const [value, setValue] = useState<null | string>(null)
return <TextInput<null | string>
name="simpleInputControlled"
onChangeValue={setValue}
value={value}
/>
}Common properties
- "name", "declaration" (label), "description" and "placeholder".
- "required", "minimum", "maximum", "minimumLength", "maximumLength", "pattern" and "invertedPattern" for validation, each with a matching "...Text" property to customize the message.
- "showInitialValidationState": Shows validation errors before the user touched the input.
- "disabled", "tooltip", "leadingIcon" and "trailingIcon".
- "type": "string" (default), "number", "integer", "float", "currency", "boolean", "date", "date-local", "datetime", "datetime-local", "time", "time-local", "week", "month" or "range".
- "model": All of the above as one object, e.g. generated from a backend schema.
Examples
Numbers
const Application = () =>
<TextInput<number>
declaration="Number"
description="Place a number please."
name="number"
placeholder="100000"
maximum={200000}
minimum={10}
required
type="number"
/>Universal date input
Dates are handled as seconds since 1970 in UTC:
const Application = () =>
<TextInput<number>
default={
new Date('2025-01-01T00:00:00.000Z')
.getTime() / 1000
}
name="timeInput"
type="date"
/>Local date input
const Application = () =>
<TextInput<string>
default="2025-01-01T23:00:00.000Z"
name="timeInput"
type="date-local"
/>Selection
const Application = () =>
<TextInput<string>
declaration="Selection Example"
name="Example selection"
selection={['A', 'B', 'C']}
/>Selection with mapped labels
const Application = () =>
<TextInput<string>
name="Another selection example"
required
selection={[
{value: 'A', label: 'a'},
{value: 'B', label: 'b'},
{value: 'C', label: 'c'}
]}
/>Search with suggestions
"suggestionCreator" may return suggestions directly or as promise, e.g. from a server. Running requests are aborted via the given "abortController" when the query changes:
const Application = () =>
<TextInput<string>
name="person"
searchSelection
suggestionCreator={async ({abortController, query}) =>
query.length < 3 ?
[] :
(await fetch(
`/api/people?query=${encodeURIComponent(query)}`,
{signal: abortController.signal}
)).json()
}
/>Code editor
const Application = () =>
<TextInput<string>
className="text-input--code-editor"
editor="code(js)"
rows={6}
initialValue="const value = 2"
/>Rich text input
With "selectableEditor" the user can switch between the editor and a plain text area:
const Application = () =>
<TextInput<string>
className="text-input--richtext-editor"
declaration="richtext"
description="Please your styled text here."
name="RichText"
placeholder="Hello Mr. Smith,<br><br>this is a Placeholder."
editor="richtext"
rows={6}
selectableEditor
initialValue="Hello Mr. Smith,<br><br>how are you?"
minimumLength={10}
maximumLength={100}
required
onChangeValue={(value) => {
console.log('Current value is', value)
}}
/>Selecting and uploading files
const Application = () =>
<FileInput name="fileInput" />Checkbox
const Application = () => <Checkbox name="accepted" required />Lists of any inputs
"Inputs" renders a list where the user adds and removes entries. The child function renders each entry:
import type {CheckboxTypes, InputsTypes} from 'react-input-material'
import {Checkbox, Inputs} from 'react-input-material'
import {useMemorizedValue} from 'react-generic-tools'
const Application = () =>
<Inputs<boolean | null, CheckboxTypes.Props>
model={useMemorizedValue({
default: [{
type: 'boolean',
value: false,
required: true,
showInitialValidationState: true
}],
name: 'checkboxInputs'
})}
createItem={useMemorizedValue(({
index, item, properties: {name}
}: InputsTypes.CreateItemOptions<
boolean | null,
CheckboxTypes.Props,
InputsTypes.Properties<boolean | null, CheckboxTypes.Props>
>): CheckboxTypes.Props => ({
...item,
name: `${name}-${String(index + 1)}`
}))}
maximumNumber={2}
minimumNumber={2}
showInitialValidationState
>
{({properties}) => <Checkbox {...properties} />}
</Inputs>Interval
Start and end are times of day in seconds since midnight:
const Application = () =>
<Interval
name="Interval example"
required
step={60}
value={{
start: {default: 120, maximum: 3600},
end: {default: 240, minimum: 120}
}}
/>Theming and tooltips
Every component accepts "themeConfiguration" with RMWC theme options and "tooltip" with a text to show on hover. "WrapConfigurations" applies both to any other content:
<TextInput
name="email"
themeConfiguration={{primary: '#d55e5d'}}
tooltip="We never share your address."
/>End-to-end tests
Each component comes with a Playwright harness which hides its internal structure from your tests:
import textInput from 'react-input-material/components/TextInput/harness'
const email = textInput(page.locator('.email'))
await email.fill('[email protected]')
expect(await email.inputValue()).toBe('[email protected]')Development
yarn install
yarn start
yarn test
yarn test:end-to-end"yarn start" serves a playground with all components. The end-to-end tests expect it to be running.
