Search code examples
javascriptreactjsreact-hookssweetalert

React onChange not working for input inside functional component


I have done this a million time and never had this problem and i don't know what i am doing wrong. I have a simple input field and have a hook useState of amount and setAmount and I am using handleChange function to update this but the handleChange function is not triggering

const CustomAmount = () => {
  const [amount, setAmount] = useState(1);

  const handleChange = (e) => {
    console.log(e); // This is not working either

    setAmount(e.target.value);
  };
  return (
    <div className="custom-amount-container">
      <h4>Enter your desired amount</h4>
      <input
        type="number"
        name="custom-amount"
        data-test="custom-amount-input"
        value={amount}
        onChange={handleChange}
      />
    </div>
  );
};

I tried putting it inside the onChange prop directly but still no luck and also normally if onChange function doesn't work it doesn't change value but in this case value is being changed inside the input field

Also I am using this component inside sweetalert modal

 const customAmountModal = () => {
    return swal(<CustomAmount />);
  };

Solution

  • I have been trying to debug the cause of event handlers not getting invoked for the component that is wrapped inside swal but couldn't. So as per my limited understanding the React Synthetic Events are not getting triggered for such components but if you use the Native DOM Events, you can achieve the same functionality like so :-

    import { useEffect, useRef, useState } from "react";
    import swal from "@sweetalert/with-react";
    import "./styles.css";
    
    const CustomAmount = () => {
      const [amount, setAmount] = useState(1);
      const inputRef = useRef(null);
      const handleChange = (e) => {
        console.log(e.target.value);
        setAmount(e.target.value);
      };
    
      console.log("render", amount);
    
      useEffect(() => {
        inputRef.current.addEventListener("input", handleChange);
      }, []);
      return (
        <div className="custom-amount-container">
          <h4>Enter your desired amount</h4>
    
          <input
            type="number"
            name="custom-amount"
            data-test="custom-amount-input"
            value={amount}
            ref={inputRef}
          />
        </div>
      );
    };
    
    export default function App() {
      const customAmountModal = () => {
        return swal(<CustomAmount />);
      };
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <button onClick={customAmountModal}>Click me</button>
        </div>
      );
    }
    
    

    Here is the codesandbox link - https://codesandbox.io/s/mystifying-jang-jrgex?file=/src/App.js

    Still would like to know why the React way doesn't work. Haven't really worked with swal so unaware of the use-cases it's made for.