Home > Back-end >  React component with props returning strange error (Typescript)
React component with props returning strange error (Typescript)

Time:08-29

I get a strange error of " ':' expected." I'm not sure but maybe I'm doing something bad with props setting for the onChange

This is my component code:

import React from "react";

interface TextFieldProps {
    label?: string;
    placeholder?: string;
    value?: string;
    onChange?: (e: any) => void;
}

export default function TextField({
    label,
    placeholder,
    value,
    onChange,
}: TextFieldProps) {
    return (
    <>
        <div className="w-full">
            <label htmlFor="textfield" className="flex justify-start w-full text-gray-700 font-medium">
                {label}
            </label>
        </div>
        <div className="mt-1">
            <input
                type="text"
                name="textfield"
                id="textfield"
                className="shadow-sm focus:ring-[#3182CE] focus:border-[#3182CE] block w-full border-gray-300 rounded-md"
                placeholder={placeholder}
                value={value}
                onChange={(e) => onChange?(e.target.value)}
            />    
        </div>
    </>
    );
}

CodePudding user response:

There is syntax error in onChange:

import React from "react";

interface TextFieldProps {
    label?: string;
    placeholder?: string;
    value?: string;
    onChange?: (e: any) => void;
}

export default function TextField({
    label,
    placeholder,
    value,
    onChange,
}: TextFieldProps) {
    return (
    <>
        <div className="w-full">
            <label htmlFor="textfield" className="flex justify-start w-full text-gray-700 font-medium">
                {label}
            </label>
        </div>
        <div className="mt-1">
            <input
                type="text"
                name="textfield"
                id="textfield"
                className="shadow-sm focus:ring-[#3182CE] focus:border-[#3182CE] block w-full border-gray-300 rounded-md"
                placeholder={placeholder}
                value={value}
                onChange={(e) => onChange?.(e.target.value)} // <-- Change this
            />    
        </div>
    </>
    );
}

CodePudding user response:

You have a syntax error in your onChange listener. It should be:

(e) => onChange?.(e.target.value)

Read more about optional chaining at MDN Docs

  • Related