Skip to content

Commit b882205

Browse files
committed
Add new handler to ensure focus is not lost when removing a selected tag element
1 parent ac0cb3c commit b882205

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

lib/ReactTags.js

+22-5
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ class ReactTags extends React.Component {
4949
onInput: this.handleInput.bind(this),
5050
onKeyDown: this.handleKeyDown.bind(this)
5151
}
52+
53+
this.container = React.createRef()
5254
}
5355

5456
componentWillReceiveProps (newProps) {
@@ -148,9 +150,24 @@ class ReactTags extends React.Component {
148150
}
149151
}
150152

151-
handleTagClick (i) {
152-
this.deleteTag(i)
153-
this.input.input.focus()
153+
handleDeleteTag (index, event) {
154+
// Because we'll destroy the element with cursor focus we need to ensure
155+
// it does not get lost and move it to the next interactive element
156+
if (this.container.current) {
157+
const interactiveEls = this.container.current.querySelectorAll('a,button,input')
158+
159+
const currentEl = Array.prototype.findIndex.call(interactiveEls, (element) => {
160+
return element === event.currentTarget
161+
})
162+
163+
const nextEl = interactiveEls[currentEl - 1] || interactiveEls[currentEl + 1]
164+
165+
if (nextEl) {
166+
nextEl.focus()
167+
}
168+
}
169+
170+
this.deleteTag(index)
154171
}
155172

156173
addTag (tag) {
@@ -189,7 +206,7 @@ class ReactTags extends React.Component {
189206
key={i}
190207
tag={tag}
191208
classNames={this.state.classNames}
192-
onDelete={this.handleTagClick.bind(this, i)}
209+
onDelete={this.handleDeleteTag.bind(this, i)}
193210
/>
194211
))
195212

@@ -199,7 +216,7 @@ class ReactTags extends React.Component {
199216
this.state.focused && classNames.push(this.state.classNames.rootFocused)
200217

201218
return (
202-
<div className={classNames.join(' ')} onClick={this.handleClick.bind(this)}>
219+
<div ref={this.container} className={classNames.join(' ')} onClick={this.handleClick.bind(this)}>
203220
<div className={this.state.classNames.selected} aria-live='polite' aria-relevant='additions removals'>
204221
{tags}
205222
</div>

0 commit comments

Comments
 (0)