I have a common List in mind which looks something like this:
it has one remove button
one input in which user can enter the name of element and on clicking insert the element will be added in the list.
For this i have added HOC like this:
function ListHOC(Component, data, listName, placeholder) {
return class extends React.Component {
constructor() {
super();
this.state = { data, element: "" };
}
add = item => {
const { data } = this.state;
data.push(item);
this.setState({ data });
};
remove = keyToRemove => {
const { data } = this.state;
const newData = data.filter(({ key }) => keyToRemove !== key);
this.setState({ data: newData });
};
render() {
const { data, element } = this.state;
const updatedList = data.map(({ name, key }) => (
<div style={{ display: "flex" }} key={key}>
<div>{name}</div>
<button onClick={() => this.remove(key)}>remove</button>
</div>
));
return (
<>
<div>{listName}: </div>
<Component data={updatedList} {...this.props} />
<input
placeholder={placeholder}
onChange={e => this.setState({ element: e.target.value })}
/>
<button
onClick={() => this.add({ name: element, key: data.length + 1 })}
>
insert
</button>
</>
);
}
};
}
one thing i am not sure about is weather to use the input
and button
and listname inside HOC or not
link to codepen: https://codepen.io/saxenanihal95/pen/NWKVJOx?editors=1010