Skip to content

Instantly share code, notes, and snippets.

@cevr
Last active June 6, 2019 23:56
Show Gist options
  • Save cevr/39a890718340f7f84bd1a17df9e835bf to your computer and use it in GitHub Desktop.
Save cevr/39a890718340f7f84bd1a17df9e835bf to your computer and use it in GitHub Desktop.
With Hooks
import React, { useState, useRef, useEffect } from 'react';
import { findDOMNode } from 'react-dom';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Radio from '@material-ui/core/Radio';
import clsx from 'clsx';
import { useStore, useActions } from 'easy-peasy';
import { EditableText } from 'shared';
import { CONFIG_ACTIONS } from 'models/configuration';
function ConfigLists() {
const { configs, lastAction } = useStore(state => ({
configs: state.configuration.configs,
lastAction: state.configuration.lastAction,
}));
const updateConfiguration = useActions(actions => actions.configuration.updateConfiguration);
const [shouldOutline, setShouldOutline] = useState(false);
const lastItem = useRef();
function handleSelect(id) {
const items = configs.map(config =>
config.id === id ? { ...config, isSelected: true } : { ...config, isSelected: false },
);
updateConfiguration({ type: CONFIG_ACTIONS.EDIT, items });
}
function handleEdit({ name, id }) {
const items = configs.map(config => (config.id === id ? { ...config, name } : config));
updateConfiguration({ type: CONFIG_ACTIONS.EDIT, items });
}
useEffect(() => {
if (lastAction === CONFIG_ACTIONS.ADD) {
const node = findDOMNode(lastItem.current);
node.scrollIntoView(true);
setShouldOutline(true);
setTimeout(() => {
setShouldOutline(false);
}, 3000);
}
}, [configs, lastAction]);
return (
<List>
{configs.map((config, index, arr) => {
const selected = config.isSelected;
const isLastItem = index === arr.length - 1;
return (
<ListItem
key={config.id}
onClick={() => handleSelect(config.id)}
className={clsx('listItem', {
active: selected,
outline: isLastItem && shouldOutline,
})}
{...(isLastItem ? { ref: lastItem } : {})}
>
<Radio checked={selected} />
<ListItemText
primary={
<EditableText
value={config.name}
onCommit={name => handleEdit({ name, id: config.id })}
/>
}
/>
</ListItem>
);
})}
</List>
);
}
export default ConfigLists;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment