peterrwilson99 / form-builder-mui

https://form-builder-ts.vercel.app
0 stars 0 forks source link

`Properties.ArrayComponent` function correction #4

Closed peterrwilson99 closed 1 year ago

peterrwilson99 commented 1 year ago

If editing any elements with an ArrayComponent property, once the Property pane has been exited, on reenter all the options dissapear. This is due to the options not being mapped correctly. As seen in the screenshots of the console logs. The issue is likely in the handleOptionChange function within ArrayComponent.

Before pane was exited: image

After pane is re-entered image

Current ArrayComponent function

const ArrayComponent = (label: string, value: OptionType[] | undefined, handleChange: (event: any) => void) => {
    const [options, setOptions] = useState(value ?? [''] as OptionType[]);

    const handleOptionChange = (index: number) => (event: React.ChangeEvent<HTMLInputElement>) => {
        const newOptions = [...options];
        newOptions[index] = { label: event.target.value, value: index };  // Ensure this is an OptionType object
        setOptions(newOptions);
        const keyedOptions = newOptions.map((option, index) => ({ value: index, label: option.label ?? '' }));
        console.log("keyedOptions", keyedOptions)
        handleChange({ target: keyedOptions });  // Mimic event object structure for consistency
    };

    const handleAddOption = () => {
        setOptions([...options, {label: '', value: options.length}]);
    };

    return (
        <div>
            <InputLabel>{label}</InputLabel>
            {(options ?? []).map((option, index) => (
                <TextField
                    key={index}
                    sx={{marginY: "16px"}}
                    variant="standard"
                    value={option.label ?? option.value ?? option}
                    onChange={handleOptionChange(index)}
                    fullWidth
                />
            ))}
            <Button onClick={handleAddOption} variant="outlined">+ Add Option</Button>
        </div>
    );
};
peterrwilson99 commented 1 year ago

Solved