reactjsmaterial3

Material-web-component onChange not working


I am trying to make a signup form and want to get the live values in react with useState using material3 web. But onChange is not working with the component. How can I achieve this?

This is the code I am using.

import { React, useState } from "react";
import "@material/web/textfield/outlined-text-field.js";

const Otp = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  const handleChange = (event) => {
    const { target } = event;
    const { name, value } = target;
    if (name === "name") setName(value);
    else if (name === "email") setEmail(value);
    console.log("handling change");
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    // Submit your form data here
    alert(`Name: ${name}, Email: ${email}`);
  };
  return (
    <md-outlined-text-field
      style={{ margin: "0 1rem" }}
      label="Phone Number"
      type="tel"
      onChange={handleChange}
    ></md-outlined-text-field>
  );
};

export default Otp;

I tried the code given above. The onChange function is not being called.


Solution

  • In the source code the text field component fires a 'input' (among others like change and select) event, more on that here. Which is equivalent to OnInput in react.

    So you can use it this way:

    <md-outlined-text-field
      style={{ margin: "0 1rem" }}
      label="Phone Number"
      type="tel"
      onInput={event => {handleChange(event)}}
    ></md-outlined-text-field>