Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling select options in React Hooks

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>
like image 474
Steven Collins Avatar asked Sep 26 '19 10:09

Steven Collins


People also ask

How do you get the selected value of dropdown in React hooks?

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 do you select options in React?

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.

How do you set the value of a select in React Hook form?

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.

How do you populate a dropdown using React?

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.


1 Answers

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
like image 100
Ashif Zafar Avatar answered Sep 19 '22 06:09

Ashif Zafar