How to build a form using stateless components?


#1

Can someone show me sample code/explanation on how to build a form using stateless components? Specifically, a create form that inserts the input value to a collection.

Here is my current create form:

class App extends React.Component {
  constructor(props) {
   super(props);

   this.state = {
        name: '',
        school: '',
      };
 }


  /*in order to access state from within function, I had to bind this when I made
  the call to submitCandidate i.e. onClick={this.submitCandidate.bind(this)}
  */
  submitCandidate(event){
    event.preventDefault();
    //assign the form fields to candidates object
    var newCandidate = {
      name: this.state.name,
      school: this.state.school,
      date: this.state.date
    }
    //insert candidates object to database
    // Candidates.insert(newCandidate);
    Meteor.call('candidateInsert', newCandidate, function(error,result){
      if(error)
        return alert(error.reason);
    });
    }

  render() {
    return (
      <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
        <div>
        <TextField
          hintText={"Enter Your Name"}
          floatingLabelText={"Name"}
          value={this.state.name}
            onChange={e => this.setState({ name: e.target.value })}
        />
        <TextField
          hintText={"Enter Your School"}
          floatingLabelText={"School"}
          value={this.state.school}
          onChange={e => this.setState({ school: e.target.value })}
        />

        <RaisedButton type="submit" label="Submit" onClick={this.submitCandidate.bind(this)} />

          </div>
      </MuiThemeProvider>
    );
  }
}

#2

Best solution I could find is using refs inside the textField components and nesting them in a higher order component.


#3

I use ref’s on all the fields and have a function in the component which does the action.