React | Select Amount - reactjs

I have a Dialog where the user is able to create a new Tour. I want to add a Select option to choose the amount of Tours being created. Currently the component is not rerendering onChange and the amount is not being saved. I would really appreciate help :)
My Code looks like this :
const [selectedOption, setSelectedOption] = useState({amount:''});
const handleSelectChange = (event) => {
const amount = event.target.amount;
setSelectedOption({
...selectedOption,
[amount]: event.target.value,
});
};
<FormControl className={classes.formControl}>
<InputLabel
htmlFor="text-simple"
required
>{t('Anzahl Touren')}</InputLabel>
<Select
native
value={selectedOption.amount}
onChange={handleSelectChange}
inputProps={{
amount: 'amount'
}}
>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
<option value={4}>4</option>
</Select>
</FormControl>
EDIT:
Getting error: Every child in a list should have a unique key prop.
const numberList = ['1','2','3','4','5']
<FormControl className={classes.formControl}>
<InputLabel
htmlFor="text-simple"
required
>{t('Anzahl Touren')}</InputLabel>
<Select
name="amount"
input={<Input id="text-simple"/>}
required
native
value={selectedOption.amount}
onChange={handleSelectChange}
>
{numberList.map((amount,index) => {
return(
<option
key={index}
value={amount}>
{amount}
</option>
)
})}
</Select>
</FormControl>

Try this approach,
Set a name field for select. And update the state based on the name field.
like below,
<Select
name="amount" <--- Add this change
native
value={selectedOption.amount}
onChange={handleSelectChange}
inputProps={{
amount: "amount"
}}
>
handleSelectChange method:-
const amount = event.target.name;
Complete Code:-
import { FormControl, InputLabel, Select } from "#material-ui/core";
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [selectedOption, setSelectedOption] = useState({ amount: "" });
const handleSelectChange = (event) => {
console.log(event.target.name, event.target.value);
const amount = event.target.name;
setSelectedOption({
...selectedOption,
[amount]: event.target.value
});
};
return (
<>
<FormControl>
<InputLabel htmlFor="text-simple" required>
Anzahl Touren
</InputLabel>
<Select
name="amount"
native
value={selectedOption.amount}
onChange={handleSelectChange}
inputProps={{
amount: "amount"
}}
>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
<option value={4}>4</option>
</Select>
</FormControl>
Selected Amount - {selectedOption.amount}
</>
);
}
Working code - https://codesandbox.io/s/proud-wave-4dz0u?file=/src/App.js:0-1080

Related

Can't take value from Input Type ="select"

I am trying to take value from a drop down menu but isn't able to do so .
My code for the dropdrop is :
<Input type="select" name="type" id="etype" value={this.state.type} onChange={this.changeTypeHandler}>
<option value="Doctor">Doctor</option>
<option value ="Nurse"> Nurse</option>
</Input>
while my changeTypeHandler is
changeTypeHandler = (event) => {
this.setState({ type: event.target.value });
}
I have seen this.state.selectedValue in on of the solution for type . So what should be done in this case ?
Sorry If its a basic question but I am new to react and isn't able to find the solution for this .Thanks
Try it like this :
<select name="type" id="etype" value={this.state.selectedValue}
onChange={this.changeTypeHandler}>
<option value="Doctor">Doctor</option>
<option value ="Nurse"> Nurse</option>
</select >
and for onChange function
changeTypeHandler =(event) =>
{
this.setState({selectedValue:event.target.value});
}
hi there you can use this instead of that
function get_selected_input() {
alert(document.querySelector('#etype').value)
}
<select type="select" name="type" id="etype" onChange=get_selected_input(this)>
<option value="">Select Option</option>
<option value="Doctor">Doctor</option>
<option value ="Nurse"> Nurse</option>
</select>
You need to use value instead of selectedValue.
changeTypeHandler = (event) => {this.setState({type: event.target.value})}
Its better todo it in the Reactjs way, which means you can use select tag
<select value={this.state.value} onChange={this.handleChange}>
<option value="Doctor">Doctor</option>
<option value="Nurse">Nurse</option>
</select>
and the handeler
handleChange(event) {
this.setState({value: event.target.value});
}
and this way of doing it is also recomanded by React official web site.
Try this
import React from "react";
import { Input } from "reactstrap";
export default class App extends React.Component {
state = {
type: ""
};
changeTypeHandler = (e) => {
this.setState({ type: e.target.value });
};
render() {
console.log(this.state)
return (
<div className="App">
<Input
type="select"
name="type"
id="etype"
value={this.state.type}
onChange={this.changeTypeHandler }
>
<option value="Doctor">Doctor</option>
<option value="Nurse"> Nurse</option>
</Input>
</div>
);
}
}

How do I reset a dropdown selector to its default value after a state reset? When I use the event handler below it doesn't revert

------------------form jsx-----------------------------
<label htmlFor = 'size'>
What size pizza would you like?
<br/>
<select name = 'size' id = 'sizeinput' onChange = {inputChange}>
<option value={null}disabled selected>Select</option>
<option value='Sm'>Sm</option>
<option value='Lg'>Lg</option>
<option value='XL'>XL</option>
</select>
</label>
------------------------form submit---------------------------
const formSubmit = e => {
e.preventDefault();
axios
.post("https://reqres.in/api/users", formState)
.then(res => {
setPost(res.data);
console.log("success", post);
setFormState({
size: ""
});
})
.catch(err => console.log(err.response));
};
The default value is set by using the value prop for select, see the docs here.
Therefore, you should bind the formState.size with the value prop. That way you can initialize it with null so that it's selected by default on mount and then reset it back to null when you're done.
<select value={formState.size} name='size' id='sizeinput' onChange={inputChange}>
<option value={null} disabled>Select</option>
<option value='Sm'>Sm</option>
<option value='Lg'>Lg</option>
<option value='XL'>XL</option>
</select>
You also have to give value attribute in select input.
import React, { useState } from 'react';
import axios from 'axios';
const Dashboard = () => {
const [formState, setFormState] = useState({ size: '' });
const [post, setPost] = useState({});
const inputChange = (e) => {
setFormState({
size: e.target.value,
});
};
const onFormSubmit = (e) => {
e.preventDefault();
axios
.post('https://reqres.in/api/users', formState)
.then((res) => {
setPost(res.data);
setFormState({ size: '' });
})
.catch((err) => console.log(err.response));
};
console.log(post);
return (
<form onSubmit={onFormSubmit}>
<label htmlFor="size">
What size pizza would you like?
<br />
<select value={formState.size} name="size" id="sizeinput" onChange={inputChange}>
<option value="" disabled selected>Select</option>
<option value="Sm">Sm</option>
<option value="Lg">Lg</option>
<option value="XL">XL</option>
</select>
</label>
<button type="submit">Submit</button>
</form>
);
};
export default Dashboard;
this is where you made the mistake
<select name = 'size' id = 'sizeinput' onChange = {inputChange}>
To
<select value={formState.size} name="size" id="sizeinput" onChange={inputChange}>

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>
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 want text then access text instead of value. event.target.text.
Check the reference here. http://output.jsbin.com/vumune/4/
Just change the option value
<option selected value="Home">Home</option>
<option value="Marketing">Marketing</option>
<option value="Work">Work</option>
<option value="Head Office">Head Office</option>
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [addrtype, setAddrtype] = useState(["Normal", "Admin"])
const Add = addrtype.map(Add => Add)
const handleAddrTypeChange = (e) => {
console.clear();
console.log((addrtype[e.target.value]));
setRole(addrtype[e.target.value])
}
const [role, setRole] = useState('Normal')
const handleSubmit = (event) => {
event.preventDefault();
console.log
(`
Name: ${name}
Email: ${email}
Role: ${role}
`);
};
const UserForm = (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input
value={name}
placeholder="Name"
required
onChange={(event) => setName(event.target.value)}
></input>
<label htmlFor="email">Email</label>
<input
value={email}
placeholder="Email"
required
onChange={(event) => setEmail(event.target.value)}
></input>
<label for="role">Choose a Role:</label>
< select
onChange={e => handleAddrTypeChange(e)}
className="browser-default custom-select" >
{
Add.map((address, key) => <option key={key} value={key}>{address}
</option>)
}
</select >
<div class="wrapper">
<button type="submit" className="button">Create User</button>
</div>
</form >

Ant design - How do i auto close select ("tags" or "multiple" mode) dropdown after each selection?

I'm using ant.design select component ("tags" or "multiple" mode) in a page, i want dropdown to be automatically closes after each selection. Now it remains open and i should click on other places in the page to close the dropdown list.
import { Select } from 'antd';
const { Option } = Select;
function handleChange(value) {
console.log(`selected ${value}`);
}
ReactDOM.render(
<Select mode="multiple" placeholder="Select Countries" size="large" onChange={handleChange}>
<Option value="country1">Country1</Option>
<Option value="country2">Country2</Option>
<Option value="country3">Country3</Option>
<Option value="country4">Country4</Option>
<Option value="country5">Country5</Option>
<Option value="country6">Country6</Option>
</Select>,
mountNode,
);
Simply change first "Select" component to this:
<Select
mode="multiple"
placeholder="Select Countries"
size="large"
ref={(select) => this.countrySelect = select}
onChange={()=>{
this.countrySelect.blur()
}}>
<Option value="country1">Country1</Option>
<Option value="country2">Country2</Option>
<Option value="country3">Country3</Option>
<Option value="country4">Country4</Option>
<Option value="country5">Country5</Option>
<Option value="country6">Country6</Option>
</Select>
From the docs:
import { Select } from 'antd';
const Option = Select.Option;
function handleChange( value ) {
console.log( `selected ${value}` );
}
<Select defaultValue="lucy" style={ { width: 120 } } onChange={ handleChange }>
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="disabled" disabled>Disabled</Option>
<Option value="Yiminghe">yiminghe</Option>
</Select>
<Select defaultValue="lucy" style={ { width: 120 } } disabled>
<Option value="lucy">Lucy</Option>
</Select>
<Select defaultValue="lucy" style={ { width: 120 } } loading>
<Option value="lucy">Lucy</Option>
</Select>
Use it's own <Option>
More info: https://ant.design/components/select/
import React, { useState } from 'react'
import { Select } from 'antd'
const Option = Select.Option
const SelectComponent = () => {
const [open, setOpen] = useState('')
const handleChange = value => {
console.log(`selected ${value}`)
}
return (
<Select
showSearch
mode={'multiple'}
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
open={open}
onChange={value => {
handleChange.bind(this, value)
this.setState({ open: false })
}}
onFocus={() => setOpen(true)}
onBlur={() => setOpen(false)}
onSearch={() => setOpen(true)}
>
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="tom">Tom</Option>
</Select>
)
}
export default SelectComponent

option disabled selected not set as default value in React js dropdown

In the dropdown below, why is Select City not appearing in the dropdown as the default selection on page load ? Instead, City1 appears as the default selected option.
I have the options for default coded as :
<option value="" disabled selected>
Select City
</option>
The options are coded in another js file as below:
import React from 'react'
const cityoptions = [
{ value: '1', name: 'City1' },
{ value: '2', name: 'City2' },
{ value: '3', name: 'City3' },
....
The following is the component for dropdown.
import React from 'react'
import PropTypes from 'prop-types'
import Select from '../others/input/select'
import cityOptions from './city-options'
const InputCities = ({ value, change }) => (
<div className="edit_caste_div">
<Select
placeholder="Select option"
value={value}
valueChange={e => change('city', e)}
className="edit_city my2"
>
<option value="" disabled selected>
Select City
</option>
{cityOptions.map((e, key) => {
return <option key={key} value={e.value}>{e.name}</option>
})}
</Select>
</div>
)
InputCities.propTypes = {
value: PropTypes.string.isRequired,
change: PropTypes.func.isRequired,
}
You should add a defaultValue attribute to select and set it to the disabled value
<Select
defaultValue="Select City"
valueChange={e => change('city', e)}
className="edit_city my2"
>
<option value="Select City" disabled>
Select City
</option>
{cityOptions.map((e, key) => {
return <option key={key} value={e.value}>{e.name}</option>
})}
</Select>

Resources