I am trying to get the text value from a dropdown select using {useState} in React Hooks. I just get the value (number) rather than the text. I've copied the bits of code below which control the select dropdown. What am I missing here?
const [addrtype, setAddrType] = useState('Home')
function handleAddrTypeChange(e) {
setAddrType(e.target.value);
console.log(addrtype)
}
<select
defaultValue={addrtype}
onChange={handleAddrTypeChange}
className="browser-default custom-select">
<option selected value="1">Home</option>
<option value="2">Marketing</option>
<option value="3">Work</option>
<option value="3">Head Office</option>
</select>
To achieve this, import the useState hook from React. Call setValue inside the handleSelect function to set the state variable to the value selected from the dropdown. Finally, output the current state value on the DOM inside your JSX.
How to use HTML <select> tag in ReactJS ? HTML <select> tag is used to create a drop down list with multiple options. The <select> tag is used as outer element and the <option> element is nested within <select> tag for defining options in a list.
You can do something like this: const Form: FC = () => { const { register, handleSubmit, control, reset, setValue } = useForm(); const [color, setColor] = useState({name:"", color_id:-1}) useEffect(() => { getData(). then((result) => { console. log("Got thing data", { result }); reset({ color_id: result.
Populating the Dropdown Now that we have the basic layout of our app and the very beginning of our dropdown — we'll need to go through each object in the fruits array and create an option element for it, with the corresponding value / label. import React, {useState} from 'react'; import './App.
import React, { useState, Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
const App = () => {
const [addrtype, setAddrtype] = useState(["Work", "Home", "school"])
const Add = addrtype.map(Add => Add
)
const handleAddrTypeChange = (e) => console.log((addrtype[e.target.value]))
return (
< select
onChange={e => handleAddrTypeChange(e)}
className="browser-default custom-select" >
{
Add.map((address, key) => <option value={key}>{address}</option>)
}
</select >)
}
render(<App />, document.getElementById('root'));
Working example
https://stackblitz.com/edit/react-select-hook
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With