2018-04-13 15:33:03 +01:00
|
|
|
import React from 'react';
|
2018-05-18 14:54:21 +01:00
|
|
|
import { kebabCase, startCase } from 'lodash';
|
2018-04-13 15:33:03 +01:00
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
import {
|
|
|
|
Alert,
|
|
|
|
Col,
|
|
|
|
ControlLabel,
|
|
|
|
FormControl,
|
2018-05-18 14:54:21 +01:00
|
|
|
HelpBlock
|
2018-09-30 11:37:19 +01:00
|
|
|
} from '@freecodecamp/react-bootstrap';
|
2018-04-13 15:33:03 +01:00
|
|
|
|
2018-05-18 14:54:21 +01:00
|
|
|
import './form-fields.css';
|
|
|
|
|
2018-04-13 15:33:03 +01:00
|
|
|
const propTypes = {
|
|
|
|
errors: PropTypes.objectOf(PropTypes.string),
|
|
|
|
fields: PropTypes.objectOf(
|
|
|
|
PropTypes.shape({
|
|
|
|
name: PropTypes.string.isRequired,
|
|
|
|
onChange: PropTypes.func.isRequired,
|
|
|
|
value: PropTypes.string.isRequired
|
|
|
|
})
|
|
|
|
).isRequired,
|
|
|
|
options: PropTypes.shape({
|
|
|
|
errors: PropTypes.objectOf(
|
|
|
|
PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(null)])
|
|
|
|
),
|
|
|
|
ignored: PropTypes.arrayOf(PropTypes.string),
|
|
|
|
placeholder: PropTypes.bool,
|
|
|
|
required: PropTypes.arrayOf(PropTypes.string),
|
|
|
|
types: PropTypes.objectOf(PropTypes.string)
|
|
|
|
})
|
|
|
|
};
|
|
|
|
|
|
|
|
function FormFields(props) {
|
|
|
|
const { errors = {}, fields, options = {} } = props;
|
|
|
|
const {
|
|
|
|
ignored = [],
|
|
|
|
placeholder = true,
|
|
|
|
required = [],
|
|
|
|
types = {}
|
|
|
|
} = options;
|
|
|
|
return (
|
|
|
|
<div>
|
|
|
|
{Object.keys(fields)
|
|
|
|
.filter(field => !ignored.includes(field))
|
|
|
|
.map(key => fields[key])
|
|
|
|
.map(({ name, onChange, value, pristine }) => {
|
2018-05-18 14:54:21 +01:00
|
|
|
const key = kebabCase(name);
|
2018-04-13 15:33:03 +01:00
|
|
|
const type = name in types ? types[name] : 'text';
|
|
|
|
return (
|
2018-05-18 14:54:21 +01:00
|
|
|
<div className='inline-form-field' key={key}>
|
2018-04-13 15:33:03 +01:00
|
|
|
<Col sm={3} xs={12}>
|
|
|
|
{type === 'hidden' ? null : (
|
2018-05-18 14:54:21 +01:00
|
|
|
<ControlLabel htmlFor={key}>{startCase(name)}</ControlLabel>
|
2018-04-13 15:33:03 +01:00
|
|
|
)}
|
|
|
|
</Col>
|
|
|
|
<Col sm={9} xs={12}>
|
|
|
|
<FormControl
|
|
|
|
bsSize='lg'
|
|
|
|
componentClass={type === 'textarea' ? type : 'input'}
|
|
|
|
id={key}
|
|
|
|
name={name}
|
|
|
|
onChange={onChange}
|
|
|
|
placeholder={placeholder ? name : ''}
|
|
|
|
required={required.includes(name)}
|
|
|
|
rows={4}
|
|
|
|
type={type}
|
|
|
|
value={value}
|
|
|
|
/>
|
|
|
|
{name in errors && !pristine ? (
|
|
|
|
<HelpBlock>
|
|
|
|
<Alert bsStyle='danger'>{errors[name]}</Alert>
|
|
|
|
</HelpBlock>
|
|
|
|
) : null}
|
|
|
|
</Col>
|
2018-05-18 14:54:21 +01:00
|
|
|
</div>
|
2018-04-13 15:33:03 +01:00
|
|
|
);
|
|
|
|
})}
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
FormFields.displayName = 'FormFields';
|
|
|
|
FormFields.propTypes = propTypes;
|
|
|
|
|
|
|
|
export default FormFields;
|