Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda