I have a problem trying to focus on the input field whenever a state showSearch state is true. I am using useRef and useEffect to achieve this. So, whenever showSearch flag changes, i run useEffect hook which checks if showSearch is true and if it is, then it focuses to the HTML element references using useRef. However, there is something wrong with it because it does not run.
here is the code snippet.
const [showSearch, setShowSearch] = useState(false);
const searchInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
console.log(showSearch);
console.log(searchInputRef);
if (showSearch && searchInputRef.current){
searchInputRef.current.focus();
}}, [showSearch]);
<form onSubmit={handleSubmit} style={{ width: "100%" }}>
<InputGroup size="lg">
<Input
variant="flushed"
placeholder="Search"
_placeholder={{
opacity: 1,
color: "gray.500",`your text`
fontSize: "1.5rem",
}}
_focus={{ borderColor: "whiteAlpha.800" }}
borderColor="#FFFFFF80"
pb={"1rem"}
fontSize="2rem"
onChange={handleSearchChange}
value={searchText}
ref={searchInputRef}. // this is where i have referenced the HTML element.
/>
<InputRightElement
w={["45%", "20%"]}
justifyContent={"flex-end"}
>
{searchText.length > 0 && (
<Button
size="sm"
onClick={handleClear}
bg={"transparent"}
color={"white"}
fontSize={"1.1rem"}
_hover={{ bg: "transparent" }}
>
Clear
</Button>
)}
</InputRightElement>
</InputGroup>
</form>
Let me know if you need more information on it.
Also, I am using chakra ui for react components.
Tried using UseRef and useEffect so everytime a state flag is true, the focus is changed to the desired input element.
aavishkar gautam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.