How to fix the type error Type '(string | Element) [] is not assignable to type 'string | Element | undefined' using react and typescript?

Viewed 500

i want to add some margin before label and i was trying to do so and i get error Type '(string | Element) [] is not assignable to type 'string | Element | undefined'

below is my code,

type CheckboxProps = {
    label?: string;
}

const CheckboxComponent: React.FC<CheckboxProps> = ({
    label,
}) => {
    return (
        <>
            <input type="checkbox" />
            <Label>{label}</Label> 
        </>
    );
}


const ParentComponent = (data) => {
    const name = data.name;
    const type = data.type;
    const label = `${name} ${type}`;
    
    return (
        <Checkbox
            label = {label}
        />
        //some other logic
    );
}

Now the problem is i want to add some margin between checkbox and label. as you see from above code the label is rendered within checkbox component and i dont want to modify margin for label within Checkbox component as its reusable component.

so i tried solution below trying to add margin for label in ParentComponent and changed the type of label in CheckboxProps type to accept string or Element.

type CheckboxProps = {
    label?: string | Element;
}

const ParentComponent = (data) => {
    const name = data.name;
    const type = data.type;
    const label = [<span style={{marginLeft: '4px'}}>${name}</span>, `${type}`];
    
    return (
        <Checkbox
            label = {label}
        />
        //some other logic
    );
}

But the above code throws error Type '(string | Element) [] is not assignable to type 'string | Element | undefined'

NOTE: checkbox component is reusable component and it accepts label as string from other components. Only ParentComponent sends label like in above code.

could someone help me with this. how to fix type error or any better solution to add margin. i am new to programming. thanks.

1 Answers

Convert label type in CheckboxProps to HTMLElement. So try this for checkbox:

type CheckboxProps = {
    label?: HTMLElement;
}

const CheckboxComponent: React.FC<CheckboxProps> = ({
    label,
}) => {
    return (
        <>
            <input type="checkbox" />
            {label && (<Label>{label}</Label>)}
        </>
    );
}

And this for parent component:

const ParentComponent = (data) => {
    const name = data.name;
    const type = data.type;
    const label = <span style={{marginLeft: '4px'}}>${name} ${type}</span>;
    
    return (
        <Checkbox
            label = {label}
        />
        //some other logic
    );
}
Related