passing variable on react handler typescript

78 Views Asked by At

I wanted to pass a variable (SearchBoolean) to be logged everytime a button handler function is invoked. So I did this:

type SearchFormProps = {
    styles: React.CSSProperties;
    classNames: string;
};

const onSubmitHandler=(event: React.SyntheticEvent, isSearched?:boolean)=>{
  event.preventDefault();
   const target = event.target as typeof event.target & {
      username: { value: string };
    };
  const username = target.username.value; 
  console.log(username, isSearched);
}

export const SearchForm=({classNames, styles}: SearchFormProps)=>{
  const SearchBoolean = useContext(SearchBooleanContext);
  const {isSearched, setIsSearched} = SearchBoolean;
  // console.log('SearchBooleans', isSearched);
  return (
    <div>
      <Form onSubmit={()=>onSubmitHandler(event, isSearched)}>
      <Form.Group className="mb-3" controlId="formBasicUsername">
        <Form.Control type="text" placeholder="Enter username" name="username" />
      </Form.Group>
      <Button variant="primary" type="submit" >
        Search
      </Button>
      </Form>
    </div>
   
  );
}

but this only gave me error that the event is deprecated and not assignable. If I removed the event from the callback, it still persists to require me passing two arguments. I assigned "?" optional on argument event, but it just made it worst. Please help.

Thank you.

1

There are 1 best solutions below

0
Tony On

The error you're experiencing is because you're passing the event object incorrectly to the onSubmit handler. In your code, you're not explicitly passing the event object to the onSubmitHandler function.

 <Form onSubmit={(event)=>onSubmitHandler(event, isSearched)}>