Leslie Gao
Leslie Gao

Reputation: 131

React with Fluent UI Form onChange not working (very simple code)

I am using React with FluentUI to build a simple form, code is following

import React, { useState, FormEvent } from "react";

import { PrimaryButton } from "office-ui-fabric-react/lib/Button";

import { IUserFormValues } from "../../models/user";
import { Stack, TextField } from "@fluentui/react";

const NewUIForm = () => {
  const [user, setUser] = useState<IUserFormValues>({
    email: "",
    password: "",
  });

  const handleInputChange = (
    event: FormEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = event.currentTarget;
    setUser({ ...user, [name]: value });
  };

  const log123 = () => {
    console.log(user.email);
  };

  return (
    <Stack>
      <Stack>
        <Stack.Item grow>
          <TextField
            placeholder="UserName"
            label="User Name"
            value={user.email}
            name="email"
            onChange={handleInputChange}
          />
          <TextField
            placeholder="Password"
            label="Password"
            value={user.password}
            name="password"
            onChange={handleInputChange}
          />
        </Stack.Item>
        <PrimaryButton onClick={log123}>Add</PrimaryButton>
      </Stack>
    </Stack>
  );
};
export default NewUIForm;

every time when I type something in the TextField I will get this error

TypeError: Cannot destructure property 'name' of 'event.currentTarget' as it is null.

Can someone help me? Thanks!!

Upvotes: 4

Views: 4323

Answers (1)

Kiran LM
Kiran LM

Reputation: 1379

Fluent UI onChange function expects two parameters: event and value(optional)

(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => void

https://developer.microsoft.com/en-us/fluentui#/controls/web/textfield#implementation

You may change your handleInputChange function like this:

  const handleInputChange = (
    event: { target: HTMLInputElement },
    newValue:String
  ):void => {
    const { name } = event.target;
    setUser({ ...user, [name]: newValue });
  };

You can check this working fiddle from here

Upvotes: 3

Related Questions