user2193941 user2193941 - 3 months ago 45
React JSX Question

What is the best way to create text input Redux

I Created a simple text field component using react-redux.

This is a dumb component, so it receive a call back function to dispatch the change.

So on each change it changes its local state and on Blur it calls the call back function.

I think i'm doing too much for such a simple task it look like an overkill, is there better/shorter way to implement it?

export default class CreativeName extends Component {
constructor(props) {
super(props);
this.state = {
creativeName: props.creativeName
};
}

componentWillReceiveProps(nextProps) {
this.setState({
creativeName: nextProps.creativeName
});
}

onBlur() {
this.props.updateDraft('creativeName', this.state.creativeName);
}

onChange(e) {`enter code here`
this.setState({creativeName: e.target.value});
}

render() {
return (
<Row>
<Col lg={12} className="row-margin">
<ControlLabel>*Name</ControlLabel>
<div className="campaign-name">
<FormControl value={this.state.creativeName} type="text" onChange={(e) => this.onChange(e)}
onBlur={(e) => this.onBlur(e)} className="campaign-name-text-field" />
</div>
</Col>
</Row>
);
}
}

Answer

I really recommend that use redux-form. redux-form store input values in global state. By redux-from you can have very usable input tags of react components.

For example:

import React, { Component, PropTypes} from 'react';

export default class FormInputTextBox extends Component {
  static PropTypes = {
    field: PropTypes.object.isRequired,
    placeholder: PropTypes.string,
    disabled: PropTypes.bool
  }
  render() {
    const {field, placeholder, disabled} = this.props;
    return (
      <div>
        <input
          type="text"
          {...field}
          placeholder={placeholder}
          disabled={disabled}
        />
      </div>
    );
  }
}
Comments