Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus to input in Storybook Story

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.

like image 662
Jhig85 Avatar asked Nov 21 '25 21:11

Jhig85


1 Answers

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}
    />
    )
})
);
like image 136
Jhig85 Avatar answered Nov 23 '25 12:11

Jhig85



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!