Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda