Input fields are used in a number of ways for both collecting and displaying data from the user.
See also: Password Input, Search and Textarea.
Basic Usage
The label/input association will be handled via the passed in id
if one is supplied or via an auto-generated id
if not supplied.
Label text can be a string or a react node.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return (<><Input labelText="Label" /><Inputid="myCustomId"labelText={<span>Label <i>with node</i></span>}/></>);}
Number
import React from 'react';import { Input, InputType } from 'react-magma-dom';export function Example() {const [inputVal, setInputVal] = React.useState(1);const [hasError, setHasError] = React.useState(false);function handleChange(event) {setInputVal(event.target.value);}React.useEffect(() => {if (inputVal > 40 || inputVal < 1) {setHasError(true);} else {setHasError(false);}}, [inputVal]);return (<Inputtype={InputType.number}labelText="Number 1-40"inputWrapperStyle={{ width: '64px' }}errorMessage={hasError ? 'Please enter a number between 1 - 40' : null}helperMessage="Enter a number 1 - 40"min={1}max={40}value={inputVal}onChange={handleChange}/>);}
Phone
import React from 'react';import { Input, InputType } from 'react-magma-dom';export function Example() {const [inputVal, setInputVal] = React.useState('');const [hasError, setHasError] = React.useState(false);const phonePattern = '^[0-9]{3}-[0-9]{3}-[0-9]{4}$';function handleChange(event) {setInputVal(event.target.value);}React.useEffect(() => {if (inputVal === '' || inputVal.match(phonePattern)) {setHasError(false);} else {setHasError(true);}}, [inputVal]);return (<Inputpattern={phonePattern}labelText={<>Phone <br /> Format: 123-456-7890</>}type={InputType.tel}errorMessage={hasError ? 'Please enter a phone number' : null}value={inputVal}onChange={handleChange}/>);}
URL
import React from 'react';import { Input, InputType } from 'react-magma-dom';export function Example() {const [inputVal, setInputVal] = React.useState('');const [hasError, setHasError] = React.useState(false);const urlPattern ='^(https?:\\/\\/)?([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})(:[0-9]+)?(\\/.*)?$';function handleChange(event) {setInputVal(event.target.value);}React.useEffect(() => {if (inputVal === '' || inputVal.match(urlPattern)) {setHasError(false);} else {setHasError(true);}}, [hasError, inputVal]);return (<Inputpattern={urlPattern}labelText="URL"type={InputType.url}errorMessage={hasError ? 'Please enter a url' : null}value={inputVal}onChange={handleChange}/>);}
Disabled
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return <Input labelText="Disabled" disabled />;}
Default Value
The defaultValue
of an input can be set using the defaultValue
prop.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return <Input labelText="Default value" defaultValue="default" />;}
Value
The value
of an input can be set using the value
prop.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return <Input labelText="Value" value="abc123" />;}
Clear Value
Setting isClearable
on an input will add a button that clears the value of an input when clicked.
The button will appear when the input has a value.
Additionally a prop onClear
can be passed in which will be called when the input is cleared.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return (<InputlabelText="Value"onClear={() => console.log('input cleared...')}isClearable/>);}
Placeholder
The placeholder
text of an input can be set using the placeholder
prop.
Placeholder text should be used to provide supplemental information about the input field. It should not be
relied upon to take the place of the label text.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return <Input labelText="Email address" placeholder="yourname@example.com" />;}
Helper Message
The helperMessage
appears underneath the input field. It will not appear if an error message is present. Can be a node or a string.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {const helperMessage = (<>Helper text goes here. <a href="#">Learn more</a></>);return <Input helperMessage={helperMessage} labelText="Helper message" />;}
Error Message
If an input has an errorMessage
, the input will be styled to highlight it's error state and the error message will appear below the input field.
If an error message is present, it will replace the helper text. Can be a node or a string.
The required
prop can be used to indicate when a field is required. It is also important to indicate to the user whenever a field is required.
While React Magma provides the error styling, it is up to the consumer app to handle the validation. We recommend using a ref
on the input for accessibility.
For short forms with an error, clicking submit should bring the focus back to the input with an error. For long forms, we recommend using an alert to combine the errors and focus should be moved to the alert. See example in Form.
import React from 'react';import { Input, Button, ButtonGroup, Spacer } from 'react-magma-dom';export function Example() {const [hasError, setHasError] = React.useState(false);const [nameValue, setNameValue] = React.useState('');const inputRef = React.useRef();function submit() {if (nameValue === '') {setHasError(true);inputRef.current.focus();} else {setHasError(false);}}function reset() {setHasError(false);setNameValue('');inputRef.current.focus();}return (<><InputerrorMessage={hasError ? 'Please provide name' : null}helperMessage="* Required"labelText="Name *"onChange={event => setNameValue(event.target.value)}requiredvalue={nameValue}ref={inputRef}/><Spacer size="12" /><ButtonGroup><Button onClick={submit}>Submit</Button><Button onClick={reset} color="secondary">Reset</Button></ButtonGroup></>);}
Character Counter
Character Counter is enabled when using the maxCount
prop. As the user types past the allowable length, an error state appears showing the overrage.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return <Input maxCount={4} labelText="Default Character Counter" />;}
Input With Icon
An icon
may be included with the input, by passing in the icon
prop. An aria-label may be added using the iconAriaLabel
prop.
Functionality can be added to the icon by using the onIconClick
and onIconKeyDown
props. All clickable input icons will appear on the right.
The iconPosition
position prop is optional and takes the values left
and right
, with left
being the default for non-clickable icons.
import React from 'react';import { Input, InputType, Spinner } from 'react-magma-dom';import { EventIcon, MailOutlineIcon } from 'react-magma-icons';export function Example() {return (<><InputlabelText="Input with icon on left"icon={<MailOutlineIcon />}type={InputType.email}/><InputiconPosition="right"labelText="Input with icon on right"icon={<Spinner />}iconAriaLabel="Loading..."/><InputlabelText="Input with clickable icon on right"iconAriaLabel="Calendar"onIconClick={() => {alert('Icon clicked');}}icon={<EventIcon />}/></>);}
Input Size
The inputSize
prop can be used to control the input size. Options are medium
and large
, with medium
being the default.
import React from 'react';import { Input, InputType } from 'react-magma-dom';import { EventIcon, MailOutlineIcon } from 'react-magma-icons';export function Example() {return (<><InputlabelText="Large input with icon on left"inputSize="large"icon={<MailOutlineIcon />}type={InputType.email}/><InputlabelText="Large input with clickable icon on right"iconAriaLabel="Calendar"inputSize="large"onIconClick={() => {alert('Icon clicked');}}icon={<EventIcon />}/><InputerrorMessage="Error"inputSize="large"labelText="Large input with error"/></>);}
Inverse
isInverse
is an optional boolean prop, that may be passed in when inputs are to be displayed on a dark background.
import React from 'react';import { Card, CardBody, Input } from 'react-magma-dom';export function Example() {return (<Card isInverse><CardBody><Inputid="inputInverse"isInverselabelText="Inverse input"placeholder="Type in here"/><InputhelperMessage="Helper text"isInverselabelText="Inverse input with helper text"/><InputerrorMessage="Please fill out this field"isInverselabelText="Inverse input with error message"required/></CardBody></Card>);}
Input Label Position
When labelPosition
is set to the value left
, the input is moved inline with the label.
If multiple inputs are needed in a column display, labelWidth
can be used which takes a number value to set a width for the label based in percentage. This helps to give a uniform appearance.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return (<><Input labelText="Left aligned label" labelPosition="left" /><br /><Input labelText="Set width" labelPosition="left" labelWidth="25" /><br /><InputlabelText="Additional set width label"labelPosition="left"labelWidth="25"/></>);}
Input With Hidden Label
The isLabelVisuallyHidden
prop can be used to visually hide the text label, while still making the text available to screen readers.
This option should only be used in rare instances, such as a search field. Providing a visual label is helpful for individuals with cognitive disabilities and users who have fine motor control limitations. When there isn't a visible label, the placeholder text should match the invisible label word for word. This is so speech input users can operate the control with voice commands.
import React from 'react';import { Input } from 'react-magma-dom';import { SearchIcon } from 'react-magma-icons';export function Example() {return (<Inputicon={<SearchIcon />}isLabelVisuallyHiddenlabelText="Search"placeholder="Search"/>);}
Help Link
Some inputs require more content next to the form field, such as a help link to provide a bit of explanation to the user. If you pass children to the input field, it will render immediately after the input. the placement of the content will vary based on the label's position:
- When the label is positioned at the top, the help link will appear at the top right of the input.
- When the label is positioned on the left, the help link will appear to the right of the input.
- When the label is visually hidden, the help link will appear to the right of the input.
The container uses a flex layout to ensure the content is positioned appropriately next to the input field.
import React from 'react';import {IconButton,Input,Tooltip,Spacer,LabelPosition,ButtonSize,ButtonVariant,} from 'react-magma-dom';import { HelpIcon } from 'react-magma-icons';export function Example() {const helpLinkLabel = 'Learn more';const onHelpLinkClick = () => {alert('Help link clicked!');};return (<><InputlabelText="Help link - top label"labelPosition={LabelPosition.top}><Tooltip content={helpLinkLabel}><IconButtonaria-label={helpLinkLabel}icon={<HelpIcon />}onClick={onHelpLinkClick}size={ButtonSize.small}variant={ButtonVariant.link}/></Tooltip></Input><Spacer size="16" /><InputlabelText="Help link - left label"labelPosition={LabelPosition.left}><Tooltip content={helpLinkLabel}><IconButtonaria-label={helpLinkLabel}icon={<HelpIcon />}onClick={onHelpLinkClick}size={ButtonSize.small}variant={ButtonVariant.link}/></Tooltip></Input><Spacer size="16" /><InputlabelText="Help link - Hidden"isLabelVisuallyHiddenhelperMessage="Help link - Label Hidden"><Tooltip content={helpLinkLabel}><IconButtonaria-label={helpLinkLabel}icon={<HelpIcon />}onClick={onHelpLinkClick}size={ButtonSize.small}variant={ButtonVariant.link}/></Tooltip></Input></>);}
Change Events
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {const [message, setMessage] = React.useState('');return (<div><p><strong>Changed Value: </strong>{' '}<span id="changedValue">{message}</span></p><InputlabelText="Test value"value=""onChange={event => setMessage(event.target.value)}/></div>);}
Focus Events
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {const [, setFocused] = React.useState(false);const [message, setMessage] = React.useState('');function changeFocusedMessage() {setFocused(prevFocused => {setMessage(!prevFocused ? 'Yes' : 'No');return !prevFocused;});}return (<div><p><strong>Focused: </strong> <span id="focused">{message}</span></p><Inputid="inputFocused"labelText="Focused?"onFocus={changeFocusedMessage}onBlur={changeFocusedMessage}/></div>);}
Forward Ref
Using React's forwardRef
feature you can gain access to the reference of the internal input.
import React from 'react';import { Button, Input, Spacer } from 'react-magma-dom';export function Example() {const inputRef = React.useRef();return (<div><Input ref={inputRef} labelText="Input to be focused" /><Spacer size="12" /><ButtononClick={() => {inputRef.current.focus();}}>Click to focus input</Button></div>);}
Custom Styles
Custom styles can be passed into the Input component. The containerStyle
property will apply to the container.
Additional labelStyle
, inputStyle
and messageStyle
properties are available to style the respective elements. Please use discretion when adding custom styles.
import React from 'react';import { Input } from 'react-magma-dom';export function Example() {return (<InputcontainerStyle={{ border: '1px dotted purple', padding: '5px' }}errorMessage="Styled error message"inputStyle={{ borderRadius: '0' }}labelStyle={{ color: 'brown', fontStyle: 'italic' }}labelText="Custom Styles for input"messageStyle={{ color: 'green' }}/>);}
Testing
Passing in the testId
prop will add the data-testid
attribute to the input element for easier querying in tests.
<input labelText="Label" testId="test-id" />
Input Props
This component uses forwardRef
. The ref is applied to the input
element.
All of the standard input attributes can be provided as props and will be applied to the input
element that gets rendered.
containerStyle
Description
Style properties for the component container element
Type
React.CSSProperties
Default
-
defaultValue
Description
Default value for the form field
Type
string
Default
-
disabled
Description
If true, element is disabled
Type
boolean
Default
false
errorMessage
Description
Content of the error message. If a value is provided, the input will be styled as an error state and the error message will display.
Type
ReactNode
Default
-
helperMessage
Description
Content of the helper message.
Type
ReactNode
Default
-
icon
Description
Icon to display within the component
Type
React Element
Default
-
iconAriaLabel
Description
Text for the aria-label attribute for an icon, if provided
Type
string
Default
-
iconPosition
Description
Position within the component for the icon to appear
Type
enum, one of:
InputIconPosition.left
InputIconPosition.right
Default
right
inputSize
Description
Relative size of the component
Type
enum, one of:
InputSize.large
InputSize.medium
Default
medium
inputStyle
Description
Style properties for the input element
Type
React.CSSProperties
Default
-
inputWrapperStyle
Description
Style properties for input wrapper element
Type
React.CSSProperties
Default
-
isInverse
Description
If true, the component will have inverse styling to better appear on a dark background
Type
boolean
Default
false
isLabelVisuallyHidden
Description
If true, label text will be hidden visually, but will still be read by assistive technology
Type
boolean
Default
false
labelStyle
Description
Style properties for the label element
Type
React.CSSProperties
Default
-
labelText
Description
Content for label; can be a node or a string
Type
ReactNode
Default
-
messageStyle
Description
Style properties for the helper or error message
Type
React.CSSProperties
Default
-
onIconClick
Description
Action that will fire when icon is clicked.
Type
function
Default
-
onIconKeyDown
Description
Action that will fire when icon receives keypress.
Type
function
Default
-
placeholder
Description
Text for input placeholder
Type
string
Default
-
required
Description
If true, the form field is required
Type
boolean
Default
false
type
Description
The type attribute of the form field
Type
enum, one of:
InputType.email
InputType.file
InputType.number
InputType.password
InputType.search
InputType.text
InputType.url
InputType.tel
Default
text
value
Description
Value for the form field
Type
string
Default
-
On this page