I'm using Material UI for my react app and am trying to get the value of a select form.
This works perfectly with the following code:
<select name="role" value={props.role} onChange={props.handleInputChange}>
<option value="client">Client</option>
<option value="worker">Worker</option>
</select>
However, if I try to implement the exact same thing using Material UI
<FormControl margin="dense" className={classes.textFieldSelect}>
<InputLabel htmlFor="role" >Role</InputLabel>
<Select
value={props.role}
onChange={props.handleInputChange}
input={<Input id="role" />}
>
<MenuItem value="worker">Worker</MenuItem>
<MenuItem value="client">Client</MenuItem>
</Select>
</FormControl>
Here's the code for handInput change in my parent component:
handleInputChange(e) {
e.preventDefault();
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({ currentUser: { ...this.state.currentUser, [name]: value } });
}
The value of the select bar doesn't change when I click the menu items. However, the values do change in the TextField if I select a different role in the plain HTML element.
Any clues on what I am doing wrong?
I just spent some time debugging it and it turns out that the reason it didn't work is because the e.target.name property is undefined when I click the . I can fix this by passing in a specific name parameter when I call handleInputChange (e.g. handleInputChange('role')). Thanks for looking at it though!
Related
I am new to React and want to implement an autocomplete suggestion box for a text input box that matches only the first letters of the options available and not just any substring which is the current behaviour of HTML's <datalist>.
I have found great answers in jQuery achieving exactly the behaviour that I need. I am just having a hard time finding a way I can achieve this behaviour using React syntax.
Here are the jQuery solutions I have found so far.
How to make datalist match result from beginning only
HTML5 Datalist auto suggest shows the list that starts with the search keyword
Here is my current code structure:
<div className="form-field word-field">
<label>Word</label>
<Field list="word_list" id="word" name="word" />
{errors.word && touched.word && <div className="validation-error">{errors.word}</div>}
<datalist id="word_list">
<option>Arc</option>
<option>House</option>
<option>Handle</option>
<option>Chair</option>
<option>Door</option>
</datalist>
</div>
Can I be given any pointers on how to achieve this? What should I look into to get the behaviour I need?
Thanks!
I have developed a simple component that does this with datalist:
import { useState } from "react";
const initialOptionsArr = [
"India",
"United States",
"United Kingdom",
"Germany",
"France",
"Israel"
];
export default function App() {
const [options, setOptions] = useState(initialOptionsArr);
const handleInputChange = ({ target }) => {
if (target.value) {
const filteredOptions = initialOptionsArr.filter((option) =>
option.toLowerCase().startsWith(target.value.toLowerCase())
);
setOptions(filteredOptions);
} else {
setOptions(initialOptionsArr);
}
};
return (
<div>
<input
type="text"
list="countries"
name="mycountry"
id="countryInput"
onChange={handleInputChange}
/>
<datalist id="countries">
{options.map((item) => (
<option value={item}>{item}</option>
))}
</datalist>
</div>
);
}
This code uses useState hook and is pretty simple. Please let me know if this helps you. Here is a sandbox link of above: https://codesandbox.io/s/funny-hodgkin-7lsu5v?file=/src/App.js
I'm working on creating a select form, but I'm trying to display only flag when language is selected, however when going through options I want to display flag and language label, sort of like this:
Example of language I'm mapping bellow
flag: "🇪🇸"
key: "es"
label: "Español"
locale: "es_ES"
My current form:
<form >
<select value={lang} onChange={e => setLang(e.target.value)}>
{availableLanguages.map(language => {
return (
<option key={language.key} value={language.key}>
{language.flag}{language.label}
</option>
)
}
)}
</select>
</form>
I know I need to change my select but I haven't found a solution to achieve this without jQuery
I'm trying to use a select element with mode="multiple". I'd like for input to be disabled, meaning that a user can only choose between existing options, not enter text. How do I do this?
My element:
import { Select } from 'antd';
import 'antd/dist/antd.css';
const { Option, OptGroup } = Select;
<Select
defaultValue={['current', 'grower', 'variety', 'varietyP90']}
size={'large'}
style={{ width: '13rem' }}
onChange={value => this.setState({ yield: value })}
mode="multiple"
maxTagCount={0}
maxTagPlaceholder="Yield metrics">
<Option value="current">Current Yield</Option>
<Option value="grower">Grower Average</Option>
<Option value="variety">Variety Potential</Option>
<Option value="varietyP90">All growers' average</Option>
</Select>
Unfortunately in v3.3 there is no way to hide the search input of Select in multiple mode.
We can set the input maxlength to zero and get the wanted result.
The offering solution is kind of a hack and I don't like it personally but I couldn't find any better solution. I tried to hide the input using css but that prevents to close the drop-list because the input is used as a trigger for closing the list on focus lost event.
class TagSelect extends Select {
disableInput() {
const selects = document.getElementsByClassName(`ant-select-search__field`)
for (let el of selects) {
el.setAttribute(`maxlength`, 0)
}
}
componentDidMount() {
this.disableInput()
}
}
ReactDOM.render(
<TagSelect
defaultValue={['current']}
size={'large'}
style={{width: '100%'}}
mode="multiple"
placeholder="Yield metrics"
>
<Option value="current">Current Yield</Option>
<Option value="grower">Grower Average</Option>
<Option value="variety">Variety Potential</Option>
<Option value="varietyP90">All growers' average</Option>
</TagSelect>,
document.getElementById("container")
)
The working demo you can check here.
This is a kind of hack in ant selection component. (using css)
Ant Version: 3.26.6
<Select className="my_select_component" />
.my_select_component {
.ant-select-search__field {
display: none;
}
I'm trying to build searchable select element in React. What is really important to me is:
Avoide jQuery
Posibility to set one of options as default selected
I have list of options, which now looks like that:
<select
onChange={props.onChange}
id={props.id}
className={props.style || "form-control"}>
{!props.defaultOption ?
<option value="" selected>Select</option> :
<option value={props.defaultOptionValue} disabled selected>{props.defaultOption}</option>}
{props.options.map((item, i) => {
if (item.id === props.defaultOptionValue) return false;
return <option key={i} value={item.id}>{item.name}</option>
})}
</select>
Nothing really complicated. I pass onChange handler, id and styles. If i provide defaultOptionValue and defaultOption in props, then it means i need to check this one as selected.
Datalist works great for me, but it doesn't support safari and i want to display label inside my input, not a value, as value is id and label name of the object.
I have already checked react-select, but it's missing option to set default value.
I have tow select lists (select1 and select2) in my form, select2 depends on select2 selection, when select1 selection change options in select2 must be change this work fine but my problem is that on change don't return to default option, it gives me last index of last select2 selection,
i want on change the select2 option change and index of selected option return to 0 or default option
I am using ng-model to deal with select in angular2
this my html code:
<td *ngIf="classificationCheck"><select name="classification_type" [(ngModel)]="message.classification_type"
class="form-control" [disabled]="isReply||isForward">
<option value="" disabled default>تصنيف موضوعي</option>
<option *ngFor= "let subType of classificationTypes">{{subType}}</option>
</select></td>
and this onChange function for select1 witch update select2 options:
classificationChange( event ){
if("غير محدد"==event){
this.classificationCheck=false;
this.message.classification_type=null;
}
else{
for(let classtype of this.classifications){
if(classtype.gen==event){
if(classtype.name)
{
this.classificationTypes=[];
this.classificationCheck=true;
for(let subType of classtype.name){
this.classificationTypes.push(subType);
}
}
}
}
}
}
Put an *ngIf on your select. Set it to true. When you want to reset, set it to false then back to true very quickly.
This was the official approach in RC4 until a proper approach was made available.
If a new approach is now available in the final release of ng2, I don't know.