Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Carbon field template doesn't support react component #8

Open
emanuellopes opened this issue Jul 20, 2021 · 0 comments
Open

Carbon field template doesn't support react component #8

emanuellopes opened this issue Jul 20, 2021 · 0 comments

Comments

@emanuellopes
Copy link

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;`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant