How to set a value for TextField from Material UI with React?

Sometimes, we want to set a value for TextField from Material UI with React.

In this article, we’ll look at how to set a value for TextField from Material UI with React.

How to set a value for TextField from Material UI with React?

To set a value for TextField from Material UI with React, we set the value prop of the TextField to a state value.

And we set the onChange prop to a function that sets the state to a the value that’s inputted.

For instance, we write:

import * as React from "react";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";

export default function App() {
  const [value, setValue] = React.useState();

  return (
    <div>
      <TextField value={value} onChange={(e) => setValue(e.target.value)} />
      <Button onClick={() => setValue("")}>Reset Text</Button>
    </div>
  );
}

We call the useState hook to create the value state and the setValue function to set the value state’s value.

Next, we set the value prop of the TextField to the value prop.

And we set the onChange prop of the TextField to a function that calls setValue with e.target.value.

e.target.value has the input value of the TextField.

Next, we add a Button that has the onClick prop set to a function that calls setValue with an empty string to let us clear the input by clicking the button.

Conclusion

To set a value for TextField from Material UI with React, we set the value prop of the TextField to a state value.

And we set the onChange prop to a function that sets the state to a the value that’s inputted.