Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
How to properly set focus to a div element in React using createRef

I have a react app that I am working on, and currently, I have a custom-built dropdown that I want to open/close when a user clicks on the trigger(the arrow button), close it when a user selects an option, or close it when a user clicks outside the displayed component.

Here is my code:

For the sake of simplicity, I only added the code that I want help with.

class NavBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showCurrencies: false,
    };

    this.handleShowCurrencies = this.handleShowCurrencies.bind(this);
  }

  componentDidMount() {
    this.currencyRef = createRef();
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.showCurrencies) return this.currencyRef.current.focus();
  }

  handleShowCurrencies = () => {
    this.setState({
      showCurrencies: !this.state.showCurrencies,
    });
  };

render() {
  <div className="currency-switch" onClick={this.handleShowCurrencies}>
    {currencySymbol}
    <span>
      <button>
        <img src={`${process.env.PUBLIC_URL}/images/arrow.png`} />
      </button>
    </span>
  </div>
  {this.state.showCurrencies ? (
    <div
      className="dropdown"
      tabIndex={"0"}
      ref={this.currencyRef}
      onBlur={this.handleShowCurrencies}
    >
      {currencies?.map((currency) => (
        <div
          key={currency.symbol}
          className={`dropdown-items ${currencySymbol === currency.symbol ? "selected" : "" }`}
          onClick={() => changeCurrencySymbol(currency.symbol)}
        >
          {`${currency.symbol} ${currency.label}`}
        </div>
      ))}
    </div>
  ) : null}
}

Currently, directing focus to a div element is working fine, and clicking outside the element as well. However, clicking back on the trigger or even selecting an option is not closing the div element. It seems like it is rendering twice(take a closer look on the console): https://drive.google.com/file/d/1ObxU__SbD_Upxr6qcy5eYO4LSy6Mzq9C/view?usp=sharing

Why is that happening? How can I solve it?

P.S: I don't often ask on StackOverflow, so am not familiar with the process. Please bear with me. If you need any other info, I will be more than happy to provide it.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!