Add possibility to pass custom input component to FormField

This commit is contained in:
Andrej Ocenas
2019-03-19 13:22:35 +01:00
parent 8f0d92ef85
commit 0d84a3fbe2
3 changed files with 50 additions and 7 deletions

View File

@@ -2,7 +2,7 @@ import React from 'react';
import { shallow } from 'enzyme';
import { FormField, Props } from './FormField';
const setup = (propOverrides?: object) => {
const setup = (propOverrides?: Partial<Props>) => {
const props: Props = {
label: 'Test',
labelWidth: 11,
@@ -15,10 +15,23 @@ const setup = (propOverrides?: object) => {
return shallow(<FormField {...props} />);
};
describe('Render', () => {
it('should render component', () => {
describe('FormField', () => {
it('should render component with default inputEl', () => {
const wrapper = setup();
expect(wrapper).toMatchSnapshot();
});
it('should render component with custom inputEl', () => {
const wrapper = setup({
inputEl: (
<>
<span>Input</span>
<button>Ok</button>
</>
),
});
expect(wrapper).toMatchSnapshot();
});
});

View File

@@ -1,10 +1,12 @@
import React, { InputHTMLAttributes, FunctionComponent } from 'react';
// import React, { InputHTMLAttributes } from 'react';
import { FormLabel } from '../FormLabel/FormLabel';
export interface Props extends InputHTMLAttributes<HTMLInputElement> {
label: string;
labelWidth?: number;
inputWidth?: number;
inputEl?: React.ReactNode;
}
const defaultProps = {
@@ -12,14 +14,24 @@ const defaultProps = {
inputWidth: 12,
};
const FormField: FunctionComponent<Props> = ({ label, labelWidth, inputWidth, ...inputProps }) => {
/**
* Default form field including label used in Grafana UI. Default input element is simple <input />. You can also pass
* custom inputEl if required in which case inputWidth and inputProps are ignored.
* @param label
* @param labelWidth
* @param inputWidth
* @param inputEl
* @param inputProps
* @constructor
*/
export const FormField: FunctionComponent<Props> = ({ label, labelWidth, inputWidth, inputEl, ...inputProps }) => {
return (
<div className="form-field">
<FormLabel width={labelWidth}>{label}</FormLabel>
<input type="text" className={`gf-form-input width-${inputWidth}`} {...inputProps} />
{inputEl || <input type="text" className={`gf-form-input width-${inputWidth}`} {...inputProps} />}
</div>
);
};
FormField.displayName = 'FormField';
FormField.defaultProps = defaultProps;
export { FormField };

View File

@@ -1,6 +1,24 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render component 1`] = `
exports[`FormField should render component with custom inputEl 1`] = `
<div
className="form-field"
>
<Component
width={11}
>
Test
</Component>
<span>
Input
</span>
<button>
Ok
</button>
</div>
`;
exports[`FormField should render component with default inputEl 1`] = `
<div
className="form-field"
>