Skip to content

Instantly share code, notes, and snippets.

@parvezmrobin
Created April 6, 2020 13:24
Show Gist options
  • Save parvezmrobin/820171e45135ab9ac079f9d289bb7261 to your computer and use it in GitHub Desktop.
Save parvezmrobin/820171e45135ab9ac079f9d289bb7261 to your computer and use it in GitHub Desktop.
/**
* Parvez M Robin
* parvezmrobin@gmail.com
* Date: Apr 04, 2019
*/
import React from 'react';
import CreatableSelect from 'react-select/creatable';
import PropTypes from 'prop-types';
function TagControl(props) {
const {
isValid, options, onChange, value,
} = props;
let className = 'form-control tag ';
if (isValid === true) {
className += 'is-valid';
} else if (isValid === false) {
className += 'is-invalid';
}
const handleChange = (newValue) => {
const mappedValue = (newValue || []).map((obj) => obj.value);
onChange({ target: { value: mappedValue } }); // simulating e.target.value
};
const mappedOptions = options.map((option) => ({ label: option, value: option }));
return (
<CreatableSelect
className={className}
classNamePrefix="tag"
placeholder="Insert tags for easy searching"
formatCreateLabel={(lbl) => lbl}
isClearable
isMulti
closeMenuOnSelect={false}
menuPlacement="auto"
hideSelectedOptions
onChange={handleChange}
options={mappedOptions}
value={value.map((val) => ({ label: val, value: val }))}
/>
);
}
TagControl.propTypes = {
isValid: PropTypes.bool.isRequired,
onChange: PropTypes.func.isRequired,
options: PropTypes.arrayOf(PropTypes.string).isRequired,
value: PropTypes.arrayOf(PropTypes.string).isRequired,
};
export default TagControl;
/**
* Parvez M Robin
* this@parvezmrobin.com
* Apr 04, 2020
*/
/* eslint-env jest */
import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act } from 'react-dom/test-utils';
import pretty from 'pretty';
import { fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import TagControl from './TagControl';
/** @type {HTMLElement} */
let container = null;
beforeEach(() => {
// setup a DOM element as a render target
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
// cleanup on exiting
unmountComponentAtNode(container);
container.remove();
container = null;
});
it('should open TagControl on click', () => {
act(() => {
render(<TagControl
value={[]}
isValid
options={['1', '2', '3']}
onChange={() => {
}}
/>, container);
});
container.querySelector('input').dispatchEvent(new MouseEvent('click', { bubbles: true }));
console.log(pretty(container.innerHTML)); // expected contain an `ul`
fireEvent.click(container.querySelector('input'));
console.log(pretty(container.innerHTML)); // expected contain an `ul`
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment