How to autofocus an input element? #1864
-
In my Next.js 13 project, I've got an input component set up as per the basic example like so: import {
FC,
HTMLInputTypeAttribute,
InputHTMLAttributes,
} from 'react';
interface Props extends InputHTMLAttributes<HTMLInputElement> {
id: string;
label?: string;
type?: HTMLInputTypeAttribute;
}
const Input: FC<Props> = ({ children, className, id, label, type, ...props }) => {
return (
<div className={`${className} relative mb-3`} data-te-input-wrapper-init>
<input
type={type || 'text'}
className="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[2.15] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[te-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-neutral-200 dark:placeholder:text-neutral-200 dark:peer-focus:text-primary [&:not([data-te-input-placeholder-active])]:placeholder:opacity-0"
id={id}
placeholder={label}
{...props}
/>
{label && (
<label
htmlFor={id}
className="pointer-events-none absolute left-3 top-0 mb-0 max-w-[90%] origin-[0_0] truncate pt-[0.37rem] leading-[2.15] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[1.15rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[te-input-state-active]:-translate-y-[1.15rem] peer-data-[te-input-state-active]:scale-[0.8] motion-reduce:transition-none dark:text-neutral-200 dark:peer-focus:text-primary"
>
{label}
</label>
)}
</div>
);
}; Usage: <Input id="email" type="email" label="Email Address" /> I would like to focus on one particular
<input
autoFocus
...
/> This focuses on the input element, but throws this error on being edited: Also, this does not render the input correctly:
<input
ref={(node) => node?.focus()}
...
/> This seemingly does nothing. How would I go about focusing the input element on mount? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Have you tried focusing the element in a |
Beta Was this translation helpful? Give feedback.
I think the problem is that the
focus
method is beeing called before the component is initialized. You can try adding a ref to an input like that:and then inside the
useEffect
hookLet me know if that helped