Broken Mind
Broken Mind

Reputation: 541

Setting a value to a field using react hooks

I have a textfield, I need to set a value to it, I know I would most likely do a handleChange for this, however I am using reactHooks (useState) and I'm not sure how to hold the value when the user inputs.

const handleChange = () => {
  //something
}

const [comment, setComment] = useState();

<Grid item xs={12} sm={6}>
    <TextField
      className={classes.field}
      id="comments"
      name="comments"
      label="Comments"
      fullWidth
      onChange={handleChange}
      autoComplete="lname"
      inputProps={{
        maxLength: 250
      }}
    />
</Grid>

Upvotes: 0

Views: 104

Answers (1)

zilijonas
zilijonas

Reputation: 3775

You have to assign value attribute to your TextField:

const [comment, setComment] = useState(''); // '' stands for initial value - empty string

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

<Grid item xs={12} sm={6}>
    <TextField
      value={comment} // here you assign the comment as TextField's value
      className={classes.field}
      id="comments"
      name="comments"
      label="Comments"
      fullWidth
      onChange={handleChange}
      autoComplete="lname"
      inputProps={{
        maxLength: 250
      }}
    />
</Grid>

Upvotes: 1

Related Questions