Home > Net >  How to have a MUI TextField have an onChange and an onSubmit event?
How to have a MUI TextField have an onChange and an onSubmit event?

Time:12-30

I am using react and mui. I have a form like so:

const handleChange = (event) => {
        set_user_input(event)
    }

    const handleSubmit = () => {
        if (user_input == 'help'){
            console.log('help')
        }
        else{
            console.log('no help')
        }
    }




<form onSubmit={handleSubmit()}>
                    <label>
                        [email protected]:: {'~ >>'}
                    </label>

                    <TextField
                        id="outlined-name"
                        value={user_input}
                        onChange={e => handleChange(e.target.value)}
                    />
                </form>

The idea is to update state of a variable with the onChange method, and have the handleSubmit method fire off when the form is submitted.

As an aside, how do I stop the form from reloading the page when it is submitted? Thanks!

CodePudding user response:

There could be other issues but just for the posted code it seems that handleSubmit should call e.preventDefault() to prevent the page reload:

const handleChange = (e) => {
  set_user_input(e.target.value);
};

const handleSubmit = (e) => {
  e.preventDefault();
  if (user_input === "help") {
    console.log("help");
  } else {
    console.log("no help");
  }
};

In the output handleSubmit can be assigned to onSubmit but not to run it on site:

<form onSubmit={handleSubmit}>
  <label>[email protected]:: {"~ >>"}</label>
  <TextField id="outlined-name" value={user_input} onChange={handleChange} />
</form>
  • Related