Skip to content

Commit

Permalink
fix: memonize webform elements array
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrsky committed Feb 23, 2021
1 parent b9d0ab2 commit a6e28a2
Showing 1 changed file with 23 additions and 12 deletions.
35 changes: 23 additions & 12 deletions src/Webform.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, FormEvent } from 'react'
import React, { useState, useMemo, FormEvent } from 'react'
import axios from 'axios'

import { getAttributeValue, formToJSON } from './utils'
Expand Down Expand Up @@ -240,6 +240,27 @@ const Webform = ({ webform, customComponents, ...props }: Props) => {
}
}

/**
* Build and memonize webform elements
*
* Webform object should rarely change.
*/
const elements = useMemo(
() => [
...webform.elements.map((element) => (
<React.Fragment key={element.name}>
{renderWebformElement(element, errors[element.name], customComponents![element.type])}
</React.Fragment>
)),

/* Render default submit button if it is not defined in elements array. */
webform.elements.find((element) => element.type === 'webform_actions') === undefined && (
<button type="submit">{DEFAULT_SUBMIT_LABEL}</button>
)
],
[webform, customComponents, errors]
)

return (
<form
onSubmit={submitHandler}
Expand All @@ -249,17 +270,7 @@ const Webform = ({ webform, customComponents, ...props }: Props) => {
noValidate={props.noValidate}
data-webform-id={webform.drupal_internal__id}
>
{/* Render webform elements */}
{webform.elements.map((element) => (
<React.Fragment key={element.name}>
{renderWebformElement(element, errors[element.name], customComponents![element.type])}
</React.Fragment>
))}

{/* Render default submit button if it is not defined in elements array. */}
{webform.elements.find((element) => element.type === 'webform_actions') === undefined && (
<button type="submit">{DEFAULT_SUBMIT_LABEL}</button>
)}
{elements}
</form>
)
}
Expand Down

0 comments on commit a6e28a2

Please sign in to comment.