1

I have added a simple TextField from Material-UI into my landing page but cannot type in the React input field. I'm not sure what is causing the issue and have double-checked the following issues:

  • Proper casing of onChange (not onchange)
  • Input value must be the state
  • this.state vs state; the former causes a TypeError: Cannot read properties of undefined (reading 'state').
  • type="text" vs. type="number"; both options don't allow for typing in the text field

Below is my code for the TextField, declaring state, and handling the change in input field.

 import TextField from '@material-ui/core/TextField';
...
 const [state, setState] = useState({
    ImageNumber: '',
  });

  const handleChange = (event) => {
    setState({
      ...state,
      [event.target.number]: event.target.value,
    });
  };
...
    <TextField label="" number="ImageNumber" type="text" value={state.ImageNumber} variant="outlined" onChange={handleChange} />

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
Henrik
  • 191
  • 1
  • 17

2 Answers2

3
  • Keep state lean ( dont specify state as an object )
  • pass event object to handleChange method
 import TextField from '@material-ui/core/TextField';
...
 const [state, setState] = useState("");

  const handleChange = (event) => {
    setState(event.target.value);
  };
...
    <TextField label="" number="ImageNumber" type="text" value={state} variant="outlined" onChange={(e) => handleChange(e)} />
Phil
  • 435
  • 2
  • 9
  • 28
  • This worked! But do you have any recommendations if this is meant to be one of many text fields and the lean approach isn't sustainable? – Henrik Sep 07 '21 at 18:15
  • @Henrik yes just simply create more states for those fields – Phil Sep 08 '21 at 07:30
1
 import TextField from '@material-ui/core/TextField';
...
 const [state, setState] = useState({
    ImageNumber: '',
  });

  const handleChange = (event) => {
    setState({
      ...state,
      [event.target.name]: event.target.value,
    });
  };
...
    <TextField label="" name="ImageNumber" type="text" value={state.ImageNumber} variant="outlined" onChange={handleChange} />

Instead of a non-existent <input /> element props number, you can use the name attribute, which shouldn't show undefined.

dw_
  • 1,707
  • 1
  • 7
  • 13