How to set focus to input in storybook story?

by herminia_bruen , in category: Javascript , 8 months ago

How to set focus to input in storybook story?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 8 months ago

@herminia_bruen 

To set focus to an input in a Storybook story, you can use the useRef hook from React. Here's an example of how you can achieve this:

  1. Import the useRef hook at the top of your component file:
1
import React, { useRef, useEffect } from 'react';


  1. Create a ref for the input element in your component:
1
const inputRef = useRef(null);


  1. Use the useEffect hook to set focus to the input element when the component mounts:
1
2
3
useEffect(() => {
  inputRef.current.focus();
}, []);


  1. Assign the ref to the input element in your JSX:
1
<input ref={inputRef} />


Now, when the Storybook story containing your component is rendered, the input element should automatically be focused.