How to get Data from Material UI TextField in React

Material UI is one of the most popular UI framework for reactJS. It reduces your work and you can easily implement components. Material UI TextField is convenient for forms and this blogpost will teach you how to get data from it.

As you know, Material UI TextField is a controlled component. onChange prop is used to pull out new values from TextField whereas value prop is used to show the value of the corresponding TextField component.

In the example given below, I have two TextFields- for username and password. Using onChange prop, I save the changed text input value in the state and show the value using value prop. Go through the example to get a clear idea.

import React, { Component } from "react";
import "./App.css";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: ""
    };
  }

  setUsername = event => {
    this.setState({
      username: event.target.value
    });
  };

  setPassword = event => {
    this.setState({
      password: event.target.value
    });
  };

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <div className="Login">
            <TextField
              variant="standard"
              placeholder="Username"
              margin="normal"
              required
              onChange={this.setUsername}
              value={this.state.username}
            />
            <TextField
              variant="standard"
              placeholder="Password"
              margin="normal"
              required
              type="password"
              onChange={this.setPassword}
              value={this.state.password}
            />

            <div className="Button">
              <Button
                variant="contained"
                color="primary"
                onClick={() => {
                  alert(this.state.username + " " + this.state.password);
                }}
              >
                Log In
              </Button>
            </div>
          </div>
        </header>
      </div>
    );
  }
}

export default App;

I hope this example helped you to get data from material-ui TextField.

Similar Posts

Leave a Reply