How to set a value on a React TextField with handlechange?

68 Views Asked by At

I need to set a value after pressing a button on this textfield :

<TextField
  fullWidth
  inputProps={{ maxLength: 75 }}
  key="nomeSocial"
  id="outlined-basic"
  label="Nome Social"
  name="nomeSocial"
  onChange={(handleChange)}
  value={values.nomeSocial}
  variant="outlined"
/>

I've tried to set the value by the comand

document.getElementsByName("nomeSocial")[0].value = "..."

but the field get this way: enter image description here

and when I click somewhere the input gets empty.

is there any way to change a value of a input by javascript and have the TextField recognize it as if someone had typed it?

2

There are 2 best solutions below

0
Saif Mohamed On BEST ANSWER

You cannot use onChange like that

First, you should create a state for your value Then set this value prop into the TextField component And use the onChange properly with the right syntax to make a controlled input field in React.

See the following code:

import TextField from '@material-ui/core/TextField';

const ControlledField = () => {
const [value, setValue] = useState("");

const handleChage = (e) => {
  setValue(e.target.value)
}

return (
  <TextField
      label="Enter Text"
      variant="outlined"
      value={inputValue}
      onChange={handleInputChange}
    />
)

}

0
P. Netto On

Just change:

onChange={(handleChange)}

to:

onChange={(e) => handleChange(e.target.value)}

"e" is the change event, so you need to add it to your handleChange() function.