Skip to content

Commit

Permalink
better not to depend on settimeout as the re-render period might take…
Browse files Browse the repository at this point in the history
… a different amount of time in different situations

Signed-off-by: Bartosz Błachut <bartoszek.blach@gmail.com>
  • Loading branch information
Brotholomew committed Jan 7, 2022
1 parent 30cfdc5 commit 6bda224
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
5 changes: 4 additions & 1 deletion src/components/forms/FlatForm.tsx
Expand Up @@ -23,6 +23,7 @@ const FlatForm = (props: FlatFormInterface) => {

const [images, setImages] = useState<Image[]>([]);
const [internalFacilities, updateInternalFacilities] = useState<Facility[]>(props.initialState.facilities);
const [tagEditorFocused, setTagEditorFocused] = useState<boolean>(true)

useEffect(() => {
if (props.initialState.facilities.length > 0)
Expand Down Expand Up @@ -131,7 +132,9 @@ const FlatForm = (props: FlatFormInterface) => {
tagEditorInterface={{
addTag: addFacility,
deleteTag: deleteFacility,
initialTags: internalFacilities
initialTags: internalFacilities,
focused: tagEditorFocused,
setFocused: setTagEditorFocused
}}
/>

Expand Down
19 changes: 16 additions & 3 deletions src/components/tags/TagEditor.tsx
@@ -1,17 +1,29 @@
import {Tag} from "../../common/types/Tag";
import TagBrick from "./TagBrick";
import "./TagEditor.scss"
import {useEffect, useState} from "react";

export interface TagEditorInterface<T extends Tag> {
addTag: (name: string) => Promise<any>,
deleteTag: (tag: T) => void,
initialTags: T[]

focused: boolean,
setFocused: (flag: boolean) => void
}

const TagEditor = <T extends Tag,> (props: TagEditorInterface<T>) => {
useEffect(() => {
if (!props.focused){
document.getElementById('tag-input')?.focus();
}
});

const addTag = (name: string) => {
props.addTag(name)
.catch((e: any) => console.error(e))

props.setFocused(true);
}

const inputChange = (event: any) => {
Expand All @@ -27,9 +39,10 @@ const TagEditor = <T extends Tag,> (props: TagEditorInterface<T>) => {
event.target.value = "";

// set focus on the input again, once the component re-renders
setTimeout(() => {
document.getElementById('tag-input')?.focus();
}, 100)
props.setFocused(false);

// in case the component does not re-render, set the focus here too
document.getElementById('tag-input')?.focus();
}
}

Expand Down

0 comments on commit 6bda224

Please sign in to comment.