carbon-field-template icon indicating copy to clipboard operation
carbon-field-template copied to clipboard

Carbon field template doesn't support react component

Open emanuellopes opened this issue 3 years ago • 0 comments

Hey, I'm trying to create a new custom field with this template, but every time I add a React component I receive and react error. for example, I want to use the checkbox control from gutenberg and I can't do it because of that js error.

Screenshot

Screen 2

/**
 * External dependencies
 */
import {unescape as unescapeString, isArray} from 'lodash';

/**
 * WordPress dependencies.
 */
import React, {Component} from '@wordpress/element';
import {CheckboxControl} from '@wordpress/components';

class HierarchicalCheckbox extends Component {
	constructor(props) {
		super(props);
		this.onChange = this.onChange.bind(this);
		this.state = {
			items: this.getOptions(),
		};
	}

	/**
	 * Renders the component.
	 *
	 * @return {Object}
	 */
	render() {
		return this.renderTreeCheckbox(this.state.items);
	}

	getOptions() {
		const {field} = this.props;
		return field.options || [];
	}

	updateItemList(list = [], itemId, checked = false) {
		if (list.length < 0) {
			return [];
		}
		list.every(item => {
			if (item.id === itemId) {
				item.checked = checked;
				return list;
			}
			if (isArray(item.children)) {
				return this.updateItemList(item.children, itemId, checked);
			}
		});
		return list;
	}

	onChange(checked, id) {
		const list = this.updateItemList(this.state.items, id, checked);
		console.log(list);
		this.setState({items: list});
	}

	renderTreeCheckbox(renderItems) {
		return renderItems.map(item => {
			return (
				<div key={item.id} className="gb-cb-hierarchical-checkbox">
					<span>{unescapeString(item.name)}</span>
					<CheckboxControl
						checked={item.checked}
						onChange={ev => {
							console.log(item.id, 'id');
							this.onChange(ev, item.id);
						}}
						label={unescapeString(item.name)}
					/>
					{item.children && item.children.length && (
						<div className="gb-cb-hierarchical-checkbox__child">
							{this.renderTreeCheckbox(item.children)}
						</div>
					)}
				</div>
			);
		});
	}
}

export default HierarchicalCheckbox;`

emanuellopes avatar Jul 20 '21 16:07 emanuellopes