update checklist components

This commit is contained in:
f0x 2023-01-31 00:34:01 +01:00
commit 79c792b832
5 changed files with 104 additions and 73 deletions

View file

@ -20,15 +20,15 @@
const React = require("react");
module.exports = function CheckList({ field, header = "All", renderEntry }) {
performance.mark("RENDER_CHECKLIST");
module.exports = function CheckList({ field, header = "All", EntryComponent, getExtraProps }) {
return (
<div className="checkbox-list list">
<CheckListHeader toggleAll={field.toggleAll}> {header}</CheckListHeader>
<CheckListEntries
entries={field.value}
updateValue={field.onChange}
renderEntry={renderEntry}
EntryComponent={EntryComponent}
getExtraProps={getExtraProps}
/>
</div>
);
@ -47,38 +47,45 @@ function CheckListHeader({ toggleAll, children }) {
);
}
const CheckListEntries = React.memo(function CheckListEntries({ entries, renderEntry, updateValue }) {
const deferredEntries = React.useDeferredValue(entries);
const CheckListEntries = React.memo(
function CheckListEntries({ entries, updateValue, EntryComponent, getExtraProps }) {
const deferredEntries = React.useDeferredValue(entries);
return Object.values(deferredEntries).map((entry) => (
<CheckListEntry
key={entry.key}
entry={entry}
updateValue={updateValue}
renderEntry={renderEntry}
/>
));
});
return Object.values(deferredEntries).map((entry) => (
<CheckListEntry
key={entry.key}
entry={entry}
updateValue={updateValue}
EntryComponent={EntryComponent}
getExtraProps={getExtraProps}
/>
));
}
);
/*
React.memo is a performance optimization that only re-renders a CheckListEntry
when it's props actually change, instead of every time anything
in the list (CheckListEntries) updates
*/
const CheckListEntry = React.memo(function CheckListEntry({ entry, updateValue, renderEntry }) {
const onChange = React.useCallback(
(value) => updateValue(entry.key, value),
[updateValue, entry.key]
);
const CheckListEntry = React.memo(
function CheckListEntry({ entry, updateValue, getExtraProps, EntryComponent }) {
const onChange = React.useCallback(
(value) => updateValue(entry.key, value),
[updateValue, entry.key]
);
return (
<label className="entry">
<input
type="checkbox"
onChange={(e) => onChange({ checked: e.target.checked })}
checked={entry.checked}
/>
{renderEntry(entry, onChange)}
</label>
);
});
const extraProps = React.useMemo(() => getExtraProps?.(entry), [getExtraProps, entry]);
return (
<label className="entry">
<input
type="checkbox"
onChange={(e) => onChange({ checked: e.target.checked })}
checked={entry.checked}
/>
<EntryComponent entry={entry} onChange={onChange} extraProps={extraProps} />
</label>
);
}
);