Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can HTML onSubmit / onClick handler function have another parameter except event? [duplicate]

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>
  )
}
  
like image 654
dante Avatar asked Aug 24 '26 05:08

dante


2 Answers

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>
like image 190
Scott Marcus Avatar answered Aug 25 '26 19:08

Scott Marcus


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>
  )
like image 42
Grant Singleton Avatar answered Aug 25 '26 18:08

Grant Singleton