I’m working with WordPress/scripts, and I need to do a for loop inside jsx. I did find this post but it is fairly old (7 years). Is the answer still correct today? or are there better solutions?
My Attempt
import { __ } from "@wordpress/i18n";
import { useSelect, useDispatch } from "@wordpress/data";
import { registerPlugin } from "@wordpress/plugins";
import { PluginDocumentSettingPanel } from "@wordpress/edit-post";
import { TextControl, PanelRow } from "@wordpress/components";
class postcodePricingBeDocSidebar {
constructor() {
const TextController = (props) => {
// Get post meta
const meta = useSelect((select) =>
select("core/editor").getEditedPostAttribute("meta")
);
// Meta prefix
const metaPrefix = "_postcode_pricing_";
// Meta fields
const rows = [
"outward_code",
"postal_town",
"postal_county",
"auto_1hr",
"auto_5hr",
"auto_10hr",
"auto_weekend_evening",
"manual_1hr",
"manual_5hr",
"manual_10hr",
"manual_weekend_evening",
];
let metaString = "original";
for (var i = 0; i < rows; i++) {
// create meta string
metaString = metaPrefix + rows[i];
}
console.log(metaString);
const { editPost } = useDispatch("core/editor");
return (
<>
<PanelRow>
<TextControl
label={__(rows[i], "postcode-pricing")}
value={meta}
onChange={(value) =>
editPost({
meta: { [metaString]: value },
})
}
/>
</PanelRow>
</>
);
};
const postcodePricingBeDocSidebar = () => {
// build the panel
return (
<PluginDocumentSettingPanel
name="postcode-pricing"
title="Area Pricing"
className="postcode-pricing"
>
<TextController />
</PluginDocumentSettingPanel>
);
};
// render the panel
registerPlugin("postcode-pricing-be-doc-sidebar", {
render: postcodePricingBeDocSidebar,
});
}
}
export default postcodePricingBeDocSidebar;