docs: use functional component for mention list

This commit is contained in:
Philipp Kühn 2021-09-07 23:22:11 +02:00
parent b06a1f4364
commit 707ba29fa5

View File

@ -1,79 +1,68 @@
import React from 'react'
import React, {
useState,
useEffect,
forwardRef,
useImperativeHandle,
} from 'react'
import './MentionList.scss'
export class MentionList extends React.Component {
constructor(props) {
super(props)
export const MentionList = forwardRef((props, ref) => {
const [selectedIndex, setSelectedIndex] = useState(0)
this.state = {
selectedIndex: 0,
}
}
componentDidUpdate(oldProps) {
if (this.props.items !== oldProps.items) {
this.setState({
selectedIndex: 0,
})
}
}
onKeyDown({ event }) {
if (event.key === 'ArrowUp') {
this.upHandler()
return true
}
if (event.key === 'ArrowDown') {
this.downHandler()
return true
}
if (event.key === 'Enter') {
this.enterHandler()
return true
}
return false
}
upHandler() {
this.setState({
selectedIndex: ((this.state.selectedIndex + this.props.items.length) - 1) % this.props.items.length,
})
}
downHandler() {
this.setState({
selectedIndex: (this.state.selectedIndex + 1) % this.props.items.length,
})
}
enterHandler() {
this.selectItem(this.state.selectedIndex)
}
selectItem(index) {
const item = this.props.items[index]
const selectItem = index => {
const item = props.items[index]
if (item) {
this.props.command({ id: item })
props.command({ id: item })
}
}
render() {
return (
<div className="items">
{this.props.items.map((item, index) => (
<button
className={`item ${index === this.state.selectedIndex ? 'is-selected' : ''}`}
key={index}
onClick={() => this.selectItem(index)}
>
{item}
</button>
))}
</div>
)
const upHandler = () => {
setSelectedIndex(((selectedIndex + props.items.length) - 1) % props.items.length)
}
}
const downHandler = () => {
setSelectedIndex((selectedIndex + 1) % props.items.length)
}
const enterHandler = () => {
selectItem(selectedIndex)
}
useEffect(() => setSelectedIndex(0), [props.items])
useImperativeHandle(ref, () => ({
onKeyDown: ({ event }) => {
if (event.key === 'ArrowUp') {
upHandler()
return true
}
if (event.key === 'ArrowDown') {
downHandler()
return true
}
if (event.key === 'Enter') {
enterHandler()
return true
}
return false
},
}))
return (
<div className="items">
{props.items.map((item, index) => (
<button
className={`item ${index === selectedIndex ? 'is-selected' : ''}`}
key={index}
onClick={() => selectItem(index)}
>
{item}
</button>
))}
</div>
)
})