0

I need to set focus on tag in my functional component when it loads. I cannot make it work properly. Please help! Below is my code; Detail.js

import React,{useState,useEffect} from 'react';
const Detail=({course})=>{
const [myfocus]=useState(null);
useEffect(() => {
    setState({
    this.myfocus.focus(); //? how to set id myfocus to this.myfocus.focus()
  });

return (
   <div>
    <h4  tabindex="0"   id="myfocus">
     {course.SUBJECT} {course.CATALOG_NBR}
     </h4>

</div>
);

}; export default Detail;

user788448
  • 779
  • 1
  • 14
  • 36
  • What do you mean by focus ? What are you trying to do ? Why do you set the state ? – Arnaud Claudel Feb 17 '20 at 19:03
  • Does this answer your question? [Set focus on input after render](https://stackoverflow.com/questions/28889826/set-focus-on-input-after-render) – user3272018 Feb 17 '20 at 19:04
  • Using focus and tabIndex should be used on interactive elements, like a button. – Chad Feb 17 '20 at 19:07
  • But it will work on other HTML elements too, like `
    ` in the list of articles if you want to add a focus action to it.
    – Deykun Feb 17 '20 at 19:09

1 Answers1

0

We have autoFocus prop in React, so you can try <h4 autoFocus />.

But you can also solve this with the ref:

const h4 = useRef()

useEffec(() => 
    h4.current.focus()
)[];

return( <h4 ref={h4} /> )

You are right, that tabIndex (use camel case in React) is probably required to make it work for the h4 element.

Deykun
  • 1,298
  • 9
  • 13
  • I don't understand why you need a [] in the useEff()[]? After removing it, it works. useEffect(() => h4.current.focus()); – user788448 Feb 17 '20 at 20:05
  • I've added [] to use useEffect as a componentDidMount(), you can add setTimeout or onLoad if it doesn't work for you. useEffect without an array will work ok if you don't have additional logic in the same component (it is not rendered multiple times), but if you have something more there, the focus will be attached each time. – Deykun Feb 18 '20 at 07:24