Unform

Simple input

Simple input

This page explains how you can create a simple input with Unform.

Here we have an example of an elementary input with support for label and error message.

components/Input.js
1import React, { useRef, useEffect } from 'react'
2import { useField } from '@unform/core'
3
4export default function Input({ name, label, ...rest }) {
5 const inputRef = useRef(null)
6
7 const { fieldName, defaultValue, registerField, error } = useField(name)
8
9 useEffect(() => {
10 registerField({
11 name: fieldName,
12 ref: inputRef,
13 getValue: ref => {
14 return ref.current.value
15 },
16 setValue: (ref, value) => {
17 ref.current.value = value
18 },
19 clearValue: ref => {
20 ref.current.value = ''
21 },
22 })
23 }, [fieldName, registerField])
24
25 return (
26 <>
27 <label htmlFor={fieldName}>{label}</label>
28
29 <input
30 id={fieldName}
31 ref={inputRef}
32 defaultValue={defaultValue}
33 {...rest}
34 />
35
36 {error && <span className="error">{error}</span>}
37 </>
38 )
39}
Edit this page on GitHub