Rog
Rog

Reputation: 18670

ReactJS: best practice access input values when creating forms

I've been playing a bit with ReactJS and am really enjoying the framework.

I'm also trying to follow the rule of creating components that are stateless where possible.

I have a Settings component that includes a child SettingsForm and a SettingsWidget.

Settings holds all the states, and only pass it as props to the form and widget.

This works (and scales) well because when the state in Settings is updated, it propagates to all child components.

var Settings = React.createClass({
    getInitialState: function() {
        settings: {}
    }
})

What I am not 100% sure on is the best practice when accessing input values on SettingsForm to pass it on to the parent component.

I know I can use refs and also two-way binding to accomplish this, but neither feel very "ReactJS-like".

Is there a better of way accomplishing this that I am unaware of? For the sake of completeness, I've included the relevant code in my SettingsForm component below

var SettingsForm = React.createClass({
  getInitialState: function() {
    return {
      changed: false
    }
  },
  handleChange: function(event) {    
    this.setState({changed: true})
    this.props.handleChange(
      this.refs.emailInputFieldRef.getDOMNode().value,
      this.refs.firstNameInputFieldRef.getDOMNode().value
    )    
  },
  handleSubmit: function(event) {
    event.preventDefault();
    // Access and pass on input values to parent callback so state is updated
    this.props.handleUpdate(
      this.refs.emailInputFieldRef.getDOMNode().value,
      this.refs.firstNameInputFieldRef.getDOMNode().value
    )
    this.setState(this.getInitialState());
  },
  ...
}

Upvotes: 0

Views: 104

Answers (1)

BradByte
BradByte

Reputation: 11093

For now there is a Mixin you can use to link the input values to the state, called LinkedStateMixin that is exactly what you are looking for...

var WithLink = React.createClass({
  mixins: [React.addons.LinkedStateMixin],
  getInitialState: function() {
    return {message: 'Hello!'};
  },
  render: function() {
    return <input type="text" valueLink={this.linkState('message')} />;
  }
});

Then all you have to do is modify your handler functions on the parent component to take your inputs as variables, and pass that function down to the child component as a prop. When you want to handle the form, call that function in the props and send the state (bound with from the Mixin) as the variables.

React Docs - React Link

Upvotes: 1

Related Questions