I face with some cases onClick or onSubmit functions needs both event and parameter.
Can I do with this in react, or vanilla html tags?
Or, Just do something side effect using another functions?
const CustomFC = ({}) => {
const [ id, setId] = useState("");
const [password, setPassword] = useState("");
type FormParams = {
id: string;
password: string;
}
const customClickHandler = useCallback((params: FormParams) =>
{
dispatch(params);
}, [id, password]);
const onChangeId = useCallback((id) => setId(id),[]);
const onChangePassword = useCallback((password) => setPassword(password),[]);
<Form
onClick ={customClickHandler}
onChange={{onChangeId, onChangePassword}}
/>
}
// Form.tsx
const Form = ({
onSubmit,
onChange,
}) => {
const { onChangeId, onChangePassword } = onChange;
const handleSubmit = ( e, params ) => { // <- can this be possible?
e.preventDefault();
onSubmit(params);
}
return (
<form onSubmit={handleSubmit}>
<input ... />
<input ... />
</form>
)
}
Any native event handler will just have one event argument, but you can use the native handler to call a second function that has your custom parameters:
document.querySelector("button").addEventListener("click", function(event){
actualHandler(event, this.id, this.dataset.test, this.className);
});
function actualHandler(event, id, dataTest, classList){
console.log(event.type, id, dataTest, classList);
}
<button id="btn" data-test="foo" class="bar">Click Me</button>
Yes you can do this:
const handleClick = (event, parameter) => {
// do stuff
}
Then call it like this:
onClick={(event) => handleClick(event, parameter)}
Does that help?
In your case it would be:
return (
<form onSubmit={(event) => handleSubmit(event, parameter)}>
<input ... />
<input ... />
</form>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With