Last active
April 4, 2016 08:26
-
-
Save richtier/e203eae4922c701ee37c to your computer and use it in GitHub Desktop.
react material-ui form field validation redux es6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NewProductDescriptionField.jsx | |
import React from 'react'; | |
import { connect } from 'react-redux'; | |
import TextField from 'material-ui/lib/text-field'; | |
import { | |
setFormFieldValidityMessage, | |
setNewProductData, | |
} from '../../actions'; | |
const NEW_PRODUCT_DESCRIPTION_FIELD_NAME = 'newProductDescription'; | |
class SmartNewProductDescriptionField extends React.Component { | |
handleChange(description) { | |
this.props.dispatch(setNewProductData({description})); | |
const validityMessage = description ? '' : 'This field is required.'; | |
this.props.dispatch( | |
setFormFieldValidityMessage(NEW_PRODUCT_DESCRIPTION_FIELD_NAME, validityMessage) | |
); | |
} | |
render () { | |
const { description, errorText }; | |
return ( | |
<TextField | |
value={description} | |
errorText={errorText} | |
onChange={this.handleChange.bind(this)} | |
/> | |
); | |
} | |
} | |
SmartNewProductDescriptionField.propTypes = { | |
description: React.PropTypes.string, | |
dispatch: React.PropTypes.func, | |
errorText: React.PropTypes.string, | |
}; | |
function select(state) { | |
return { | |
description: state.newProduct.description, | |
recognising: state.newProduct.recognising, | |
errorText: state.formFieldValidityMessages[NEW_PRODUCT_DESCRIPTION_FIELD_NAME] | |
}; | |
} | |
export default connect(select)(SmartNewProductDescriptionField); | |
// actions.js | |
export const SET_FIELD_VALIDITY_MESSAGE = 'SET_FIELD_VALIDITY_MESSAGE'; | |
export function setFormFieldValidityMessage(formFieldName, message) { | |
return { formFieldName, message, type: SET_FIELD_VALIDITY_MESSAGE }; | |
} | |
// reducers.js | |
import { combineReducers } from 'redux'; | |
import { | |
SET_FIELD_VALIDITY_MESSAGE, | |
} from './actions'; | |
const formFieldValidityMessagesInitialState = { | |
'newProductDescription': '' | |
}; | |
function formFieldValidityMessages(state = formFieldValidityMessagesInitialState, action) { | |
switch (action.type) { | |
case SET_FIELD_VALIDITY_MESSAGE: | |
return Object.assign({}, state, {[action.formFieldName]: action.message}); | |
default: | |
return state; | |
} | |
} | |
export default combineReducers({formFieldValidityMessages}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment