'how to have a dropdown activate when input is focused?

I'm trying to make a reddit clone MERN and need a dropdown like the dorpdown in the reddit search bar

the styling is not an issue the issue is to make the dropdown appear when the input bar is focused

also i am using tailwindcss

can anyone please tell me how to do this?



Solution 1:[1]

const show = () => {
  document.querySelector('.content').classList.add("active")
}

const hide = () => {
  document.querySelector('.content').classList.remove("active")
}
.dropdown{
  display: flex;
  flex-direction: column;
  position: relative;
  width: 200px;
}

input{
  width: 100%;
}

.content{
  background: red;
  padding: 4px;
  position: absolute;
  top: 100%;
  width: 100%;
  display: none;
}

.active{
  display: flex;
  
  }
<div class = "dropdown">
  <input onFocus = "show()" onBlur = "hide()" />
  <div class = "content">
    Dropdown
  </div>
</div>

React and Tailwind

const Dropdown = () => {
  const [isFocus, setIsFocus] = React.useState(false);
  return (
    <div className = "w-40 border m-4">
      <input
        className = "w-full"
        onFocus={() => setIsFocus(true)}
        onBlur={() => setIsFocus(false)}
      />
      { isFocus && <div className = "bg-red-300">Dropdown</div>}
    </div>
  );
};

Solution 2:[2]

I suppose you want to show the select not just when you focus the input but also when you are interacting with the select: you may avoid JS at all and use the :focus-within pseudoclass

.dropdown select {
  display: none;
}

.dropdown:focus-within select {
  display: block;
}
<div class="dropdown">
  <input />
  <select>
    <option>option</option>
  </select>
</div>

but if you need this to be working only on input focus

.dropdown select {
  display: none;
}

.dropdown input:focus + select {
  display: block;
}
<div class="dropdown">
  <input />
  <select>
    <option>option</option>
  </select>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Fabrizio Calderan