Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  162] [ 6]  / answers: 1 / hits: 5500  / 3 Years ago, thu, february 25, 2021, 12:00:00

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 />);
};

More From » reactjs

 Answers
1

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.


[#1734] Friday, February 19, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jennie

Total Points: 593
Total Questions: 102
Total Answers: 106

Location: Federated States of Micronesia
Member since Fri, Sep 16, 2022
2 Years ago
jennie questions
;