Khant
Khant

Reputation: 1122

How to pass string only rather than the entire event in the onchange?

Hi I am now working on a project. There were 2 component inside. InputDialog & AuthenComponent. I am now trying to keep track of the string inside the HTMLTextAreaElement. My way of doing thing is working fine but one of the senior want a different way. I will now show you the working version.

InputDialog Component

interface InputDialogContentProps {
  onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => string;
}

export default function InputDialog(props: InputDialogContentProps) {
  return (
    <div className="inputDialogContent">
      <DialogContent className="dialogContentPlacement">
        <TextField
          onChange={props.onChange}
          fullWidth
        />
      </DialogContent>
    </div>
  );
}

as you can see I am getting the onchange event from the props.

This is the AuthenComponent ( Function component )

<Dialog
    open
    onClose={hideDialogBox}
    aria-labelledby="alert-dialog-title"
    aria-describedby="alert-dialog-description"
    className="TextPlacement"
>
 <div className="AuthenticationDialog">

  <InputDialogContent
     inputLabel="Email Address"
     inputType="email"
     onChange={onInputChange}/>
   </div>
  </Dialog>

function onInputChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
    setEnableLoginButton(isValidEmail(e.target.value));
    return e.target.value;
  }

const isValidEmail = (email: string): boolean => {
  const validateFormat = /^\w+([\.-]?\w+)*@\w+$/;
  return email.match(validateFormat);
};

These component are working fine. But senior want me to pass the string only rather than passing the entire event. I have been searching google for too long and can't find a soluton.

He want something like this in inputDialog

onChange: (text: string) => void

Rather than

onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => string;

Upvotes: 1

Views: 147

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370999

Extract the value from the element inside the child component's handler, and call the prop function with it:

interface InputDialogContentProps {
  checkValidEmail: (text: string) => void
}
onChange={(e) => { props.checkValidEmail(e.currentTarget.value); }}

And in the parent component:

function checkValidEmail(text: string) {
  setEnableLoginButton(isValidEmail(text));
}

Upvotes: 1

Duke
Duke

Reputation: 353

You can try

<InputDialogContent
 inputLabel="Email Address"
 inputType="email"
 onChange={(e) => onInputChange(e.target.value)}/>

then your onInputChange function

function onInputChange(email: string) {
   setEnableLoginButton(isValidEmail(email));
   return email;
}

Upvotes: 0

Related Questions