Home > Net >  React OnChange pass ID or Event
React OnChange pass ID or Event

Time:11-05

I want to pass the id and value of a textfield to a function on onChange event.

I have tried a bunch of different things but i cant return the event from onChange because it only passes the value.

My function

    const handleFieldChange = (value: any, name: string) =>
    setFields({
        ...fields,
        [name]: value,
    });

And my textfield

<TextField id="test" label="Test" onChange={(event) => handleFieldChange(event, "test")} defaultValue="Test" />

Because the "event" only contains the value and not the actual event i have to pass the ID separately and i cant just do onChange={handleFieldChange}

This seems like a ugly solution because i have hundreds of TextFields

CodePudding user response:

Considering that your event only contains the value and not the actual event, the issue most likely relies within your TextField component. Most likely the onChange implementation returns event.target.value instead of just event.

CodePudding user response:

you can access the id prop of the text field without passing as 2nd argument

const handleFieldChange = (event: React.FormEvent<HTMLInputElement>) => {
    const {id: name, value} = event.currentTarget;
    setFields({
        ...fields,
        [name]: value,
    });
}

HTML

<TextField 
    id="test" // IMP! This is used in the handler 
    label="Test" 
    onChange={handleFieldChange} 
    defaultValue="Test" 
/>
  • Related