Skip to content

Instantly share code, notes, and snippets.

@BenBroide
Created January 1, 2021 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenBroide/27a9449def4f504261b400a420909750 to your computer and use it in GitHub Desktop.
Save BenBroide/27a9449def4f504261b400a420909750 to your computer and use it in GitHub Desktop.
Repeater Field Hoc for Gutenberg
const {withSelect, withDispatch, useSelect} = wp.data
const { TextControl} = wp.components
const RepeaterControlHoc = ({field}) => {
const {meta_key, label, show_in_rest} = field
let arrayValues = useSelect(
select => select('core/editor').getEditedPostAttribute('meta')?.[meta_key]
);
const properties = show_in_rest?.schema?.items?.properties
let propertiesKeys = Object.entries(properties).map(item => item[0])
let ControlField = ({value, handleFieldChange}) => {
return <div>
<h3>{label}:</h3>
{arrayValues.map((row, index) => {
return <div>{propertiesKeys.map((propertyKey) => {
return <TextControl
label={`Set ${label} ${propertyKey} ${index+1}`}
value={arrayValues[index][propertyKey]}
onChange={value => handleFieldChange( arrayValues,index, propertyKey, value)}
/>
})}
</div>
})}
</div>
};
ControlField = withSelect(
(select) => {
return {
[meta_key]: select('core/editor').getEditedPostAttribute('meta')[meta_key]
}
}
)(ControlField);
ControlField = withDispatch(
(dispatch) => {
return {
handleFieldChange: (arrayValues,index, propertyKey, value) => {
arrayValues[index][propertyKey] = value
let arrayValuesCopy = arrayValues.splice(0)
dispatch('core/editor').editPost({meta: {[meta_key]: arrayValuesCopy}})
}
}
}
)(ControlField);
return <><ControlField/></>
}
export default RepeaterControlHoc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment