import React from "react" export interface TextListAnswerComponentProps { value?: string[] onValueChange: (value: string[]) => void onNextOrComments?: (ev: React.KeyboardEvent) => void } export default class TextListAnswerComponent extends React.Component { newLine: HTMLInputElement | null = null focus() { return this.newLine?.focus() } handleChange = (index: number, ev: React.ChangeEvent) => { const newValue = this.props.value ? [...this.props.value] : [] newValue[index] = ev.target.value return this.props.onValueChange(newValue) } handleNewLineChange = (ev: React.ChangeEvent) => { const newValue = this.props.value ? [...this.props.value] : [] newValue.push(ev.target.value) return this.props.onValueChange(newValue) } handleKeydown = (index: number, ev: React.KeyboardEvent) => { const value = this.props.value ? [...this.props.value] : [] // When pressing ENTER or TAB if (ev.keyCode === 13 || ev.keyCode === 9) { // If the index is equal to the items length, it means that it's the last empty entry let nextInput if (index >= value.length) { if (this.props.onNextOrComments != null) { this.props.onNextOrComments(ev) } } // If it equals to one less, we focus the newLine input if (index === value.length - 1) { nextInput = this.newLine nextInput!.focus() // If not, we focus the next input } else { nextInput = (this as any)[`input${index + 1}`] nextInput.focus() } // It's important to prevent the default behavior when handling tabs (or else the tab is applied after the focus change) return ev.preventDefault() } } handleRemoveClick = (index: number, ev: React.MouseEvent) => { const newValue = this.props.value ? [...this.props.value] : [] newValue.splice(index, 1) return this.props.onValueChange(newValue) } render() { const value = this.props.value || [] return ( {value.map((textLine: string, index: number) => ( ))}
{index + 1}. 
{ ;(this as any)[`input${index}`] = c }} type="text" className="form-control box" value={textLine} onChange={(ev) => this.handleChange(index, ev)} onKeyDown={(ev) => this.handleKeydown(index, ev)} autoFocus={index === value.length - 1} onFocus={(ev: React.FocusEvent) => { // Necessary or else the cursor is set before the first character after a new line is created return ev.target.setSelectionRange(textLine.length, textLine.length) }} />
{ this.newLine = c }} id="newLine" />
) } }