skip to Main Content

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 reconize it as if someone had typed it?

2

Answers


  1. 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}
        />
    )
    
    }
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search