Skip to content

Instantly share code, notes, and snippets.

@jean182

jean182/Select.jsx

Created Jan 24, 2020
Embed
What would you like to do?
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