Skip to content

Instantly share code, notes, and snippets.

@jean182
Created January 24, 2020 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jean182/6cf1097e031403585dca9505de399eb1 to your computer and use it in GitHub Desktop.
Save jean182/6cf1097e031403585dca9505de399eb1 to your computer and use it in GitHub Desktop.
import React, { Component } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { isEmpty, isUndefined } from "lodash-es";
import { makeCurrentLevel } from "redux-modules/location/hierarchy";
const LevelOption = props => {
const { level } = props;
if (!isEmpty(level)) {
const { id, attributes } = level;
const { displayName } = attributes;
return (
<option key={id} value="">
{displayName}
</option>
);
}
return null;
};
LevelOption.defaultProps = {
level: {}
};
LevelOption.propTypes = {
level: PropTypes.oneOfType([PropTypes.object])
};
class _Select extends Component {
state = {
option: {}
};
handleChange = event => {
const { nodes, onChange } = this.props;
const { value } = event.target;
console.log(value);
const matchingNode = isEmpty(value)
? {}
: nodes.find(node => node.id === value);
this.setState({ option: matchingNode });
onChange(matchingNode);
};
handleSubOptionsListChange = node => {
const { onChange, selectedOption } = this.props;
if (isEmpty(selectedOption)) {
this.setState({ option: {} });
onChange(node);
} else {
onChange(node);
}
};
render() {
const { level, nodes } = this.props;
const { option } = this.state;
return (
<div>
<select onChange={this.handleChange}>
<LevelOption level={level} />
{nodes.map(node => {
const { attributes, id } = node;
const { displayName } = attributes;
return (
<option key={id} value={id}>
{displayName}
</option>
);
})}
</select>
{!isEmpty(option) && !isUndefined(option.attributes.children) && (
<Select
nodes={option.attributes.children}
onChange={subSelections =>
this.handleSubOptionsListChange(subSelections)
}
selectedOption={option}
/>
)}
</div>
);
}
}
/* istanbul ignore next */
const makeMapStateToProps = () => {
const getCurrentLevel = makeCurrentLevel();
const mapStateToProps = (state, props) => {
return {
level: getCurrentLevel(state, props)
};
};
return mapStateToProps;
};
_Select.defaultProps = {
level: {}
};
_Select.propTypes = {
level: PropTypes.oneOfType([PropTypes.object]),
nodes: PropTypes.instanceOf(Array).isRequired,
onChange: PropTypes.func.isRequired
};
const Select = connect(makeMapStateToProps)(_Select);
export default connect(makeMapStateToProps)(Select);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment