Created
January 1, 2021 12:48
-
-
Save BenBroide/27a9449def4f504261b400a420909750 to your computer and use it in GitHub Desktop.
Repeater Field Hoc for Gutenberg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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