Skip to content

Commit

Permalink
Add first cut of form reset
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevnz committed Jun 26, 2019
1 parent d375c0b commit 5550875
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
23 changes: 20 additions & 3 deletions src/form/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import React, { createRef } from 'react'
import React, {
createRef,
forwardRef,
useImperativeHandle,
useRef,
} from 'react'
import PropTypes from 'prop-types'

/**
* Form Component.
*
*/
const Form = ({ name, onSubmit, children }) => {

const Form = forwardRef(({ name, onSubmit, children }, ref) => {
const mapped = Array.isArray(children)
? children.map(child => {
const displayName = child.type ? child.type.displayName : false
Expand All @@ -28,8 +34,19 @@ const Form = ({ name, onSubmit, children }) => {
displayName: fEl.displayName,
}))

const formRef = useRef()

useImperativeHandle(ref, () => ({
reset: () => {
formRef.current.reset()
const ins = formRef.current.querySelectorAll('input')
const els = Array.from(ins)
els.forEach(e => (e.value = ''))
},
}))
return (
<form
ref={formRef}
name={name}
className="rfe-form"
onSubmit={e => {
Expand Down Expand Up @@ -72,7 +89,7 @@ const Form = ({ name, onSubmit, children }) => {
{mapped}
</form>
)
}
})

Form.displayName = 'ReactFormElements(Form)'

Expand Down
15 changes: 13 additions & 2 deletions working/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { createRef } from 'react'
import React, { createRef, useRef } from 'react'
import ReactDOM from 'react-dom'
import './style.css'
import {
Expand All @@ -21,13 +21,15 @@ import {
} from 'react-form-elements'

const App = () => {
const ref = createRef()
const ref = useRef()
const formRef = useRef()
const { id, value, handleChange, inputRef } = useFormElement('', ref)

return (
<div>
<h1>React Form Elements</h1>
<Form
ref={formRef}
name="WorkingForm"
onSubmit={e => {
console.info('form data', e)
Expand Down Expand Up @@ -105,6 +107,15 @@ const App = () => {
>
Check
</Button>
<Button
onClick={e => {
e.preventDefault()
console.info('The button was clicked', formRef)
formRef.current.reset()
}}
>
Cancel
</Button>
</Fieldset>
</Form>
</div>
Expand Down

0 comments on commit 5550875

Please sign in to comment.