I am creating a storybook react component and trying to set focus to an input on a story. I don't want to set it on every single story. So far I have:
const InputComponent = React.forwardRef(({
inputName,
value,
}, myRef) => {
return (
<input
name={inputName}
ref={myRef}
type='text'
/>
)
}
stories.add(
"Input field - Active",
() => (
<InputComponent
inputName='Name'
)
);
I don't know if I need to use the ref or not. I have tried using autoFocus and setting it to true as a prop but that did not work. Any help appreciated.
I missed something small. I had the ref prop in the wrong spot. It should have been in the object with inputName and value. Once I moved in there I was able to use react hooks useRef and useEffect on the story to focus the input like this:
stories.add(
"Input field - Active",
() => React.createElement(() => {
const newRef = useRef(null);
useEffect(() => {
newRef.current.focus();
});
return (
<InputComponent
inputName='Name'
myRef={newRef}
/>
)
})
);