What I want is when I select "AUD" from the dropdown menu my button’s("dropbtn") innerHtml changes to "AUD" similarly other way around. I want my button to change its text to the text of the I select from my dropdown menu
Here is the code:
App.js:
import './App.css'
import React, { useState, useEffect, useRef } from "react";
export default function App() {
const [listopen, setListopen] = useState(false)
const Dropdown = () => {
if (listopen) {
setListopen(false)
} else {
setListopen(true)
}
}
return (
<main>
<nav>
<ul>
<div class="dropdown">
<li><button class="dropbtn" onClick={() => Dropdown()} >USD
</button></li>
<div class="dropdown-content" id="myDropdown" style={{ display: listopen === false ? 'none' : 'block' }}>
<a href="/">AUD($)</a>
<a href="/">USD($)</a>
<a href="/">PKR($)</a>
</div>
</div>
</ul>
</nav>
</main>
)
}
App.css:
.dropdown-content {
display: none;
position: absolute;
background-color: #1a2456;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 100;
width: 9.5vw;
}
.dropdown-content a {
float: none;
color: #fead94;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
z-index: 100;
}
>Solution :
You could use a state for the text on the button and have a click event on the dropdrown
export default function App() {
const [listopen, setListopen] = useState(false)
const [btnText, setBtnText] = useState("Default Text");
const Dropdown = () => {
setListopen(!listopen) //Same functionality as yours but less code
}
const handleOptionClick = (txt)=> {
setBtnText(txt);
}
return (
<main>
<nav>
<ul>
<div class="dropdown">
<li><button class="dropbtn" onClick={() => Dropdown()}> {btnText}
</button></li>
<div class="dropdown-content" id="myDropdown" style={{ display: listopen === false ? 'none' : 'block' }}>
<a href="/" onClick={()=> handleOptionClick("AUD")}>AUD($)</a>
<a href="/" onClick={()=> handleOptionClick("USD")}>USD($)</a>
<a href="/"onClick={()=> handleOptionClick("PKR")}>PKR($)</a>
</div>
</div>
</ul>
</nav>
</main>
)
}
Also you can modify DropDown function for less code like I did