Jordan kayinamura
Jordan kayinamura

Reputation: 13

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.

Upvotes: 1

Views: 185

Answers (0)

Related Questions