Skip to content

Instantly share code, notes, and snippets.

@jamesjwarren
Last active February 15, 2018 16:16
Show Gist options
  • Save jamesjwarren/b0facf05e8a0ce5e5daa987164e571b0 to your computer and use it in GitHub Desktop.
Save jamesjwarren/b0facf05e8a0ce5e5daa987164e571b0 to your computer and use it in GitHub Desktop.
A modified version of aor-dependent-input with support for nesting within an <EmbeddedArrayInput> from aor-embedded-array
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { mapStateToProps } from 'aor-dependent-input/lib/DependentInput';
import EmbeddedArrayInputFormField from 'aor-embedded-array/lib/mui/form/EmbeddedArrayInputFormField';
/**
* A modified version of DependentInputComponent with
* support for being nested within <EmbeddedArrayInput>
*
* @property {React.Component} DependentInputComponent
* @example
* <EmbeddedArrayInput source={source}>
* <DependentInput source="type" value="TEXT">
* <LongTextInput source="text" label="Text" />
* </DependentInput>
* </EmbeddedArrayInput>
*/
export const DependentInputComponent = ({
children,
show,
dependsOn,
value,
resolve,
...props
}) => {
if (!show) {
return null;
}
// Extrapolate prefix from source prop
let prefix = props.source.split('.');
prefix = prefix.length ? prefix[0] : prefix;
if (Array.isArray(children)) {
return (
<div>
{React.Children.map(children, child => (
<div
key={child.props.source}
style={child.props.style}
className={`aor-input-${child.props.source}`}
>
<EmbeddedArrayInputFormField
input={child}
prefix={prefix}
{...props}
/>
</div>
))}
</div>
);
}
return (
<div
key={children.props.source}
style={children.props.style}
className={`aor-input-${children.props.source}`}
>
<EmbeddedArrayInputFormField
input={children}
prefix={prefix}
{...props}
/>
</div>
);
};
DependentInputComponent.propTypes = {
children: PropTypes.node.isRequired,
show: PropTypes.bool.isRequired,
source: PropTypes.any,
value: PropTypes.any,
resolve: PropTypes.func,
formName: PropTypes.string
};
/**
* Override state to props mapping for DependentInputComponent
* map source prop => dependsOn to ensure compatibility with field
* components such as EmbbeddedArrayInput
* @param {*} state
* @param {*} props
*/
const mapStateToPropsOverride = (
state,
{ resolve, source, value, formName }
) => {
return mapStateToProps(state, {
dependsOn: source,
resolve,
value,
formName
});
};
export default connect(mapStateToPropsOverride)(DependentInputComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment