I create form, I have several TextField, DropDownMenu material-ui components included, question is how I can collect all data from all TextFields, DropDownMenus in one obj and s
The strategy of the accepted answer is correct, but here's a generalized example that works with the current version of React and Material-UI.
The flow of data should be one-way:
TextArea
s are populated from this initial statestate
via the handleChange
callback.state
is accessed from the onClick
callback---right now it just writes to the console. If you want to add validation it could go there.import * as React from "react";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
const initialState = {
error: null, // you could put error messages here if you wanted
person: {
firstname: "",
lastname: ""
}
};
export class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
// make sure the "this" variable keeps its scope
this.handleChange = this.handleChange.bind(this);
this.onClick = this.onClick.bind(this);
}
render() {
return (
{this.state.error}
);
}
onClick() {
console.log("when clicking, the form data is:");
console.log(this.state.person);
}
handleChange(event, newValue): void {
event.persist(); // allow native event access (see: https://facebook.github.io/react/docs/events.html)
// give react a function to set the state asynchronously.
// here it's using the "name" value set on the TextField
// to set state.person.[firstname|lastname].
this.setState((state) => state.person[event.target.name] = newValue);
}
}
React.render( , document.getElementById('app'));
(Note: You may want to write one handleChange
callback per MUI Component to eliminate that ugly event.persist()
call.)