Selected Value not showing in Textfield Select - Material UI React Component - reactjs

I have TextField Select Material UI components based on a certain number of value in a variable.
{this.state.selectedNextHops.map((nextHop, index) => (
<div>
<TextField
select
className="vnfprofile-field"
InputProps={{ className: 'variable-value site-details-view-textfield' }}
InputLabelProps={{ shrink: true }}
SelectProps={{
MenuProps: {
className: 'vnf-designer-value',
getContentAnchorEl: null,
anchorOrigin: {
vertical: 'bottom',
horizontal: 'left',
}
},
}}
value = {this.state.selectedNextHops[index] || ''}
disabled={this.props.newPopoverPanelView === 'VIEW' ? true : false}
onChange={(e) => this.handleChange('nexthop', e)}
>
{this.state.remainingNextHops.length !== 0 ? this.state.remainingNextHops.map((option, i) => (
<MenuItem key ={i} value = {option || ''}>
{option}
</MenuItem>
)) :
<MenuItem value = {'No Data Available'}>
{'No Data Available'}
</MenuItem>}
</TextField>
<TextField
className="vnfprofile-field subnet-textfield"
InputProps={{ className: 'variable-value' }}
InputLabelProps={{ shrink: true }}
value = {'29'}
/>
</div>
))
}
The TextFields show up sequentially when I select value from the previous dropdown and filters the menu based on previous selection.
if(selectedNextHops.indexOf(event.target.value) === -1) {
selectedNextHops.push(event.target.value);
}
remainingNextHops = this.props.nextHopSapds.filter(nextHop => selectedNextHops.indexOf(nextHop) === -1);
this.setState({
selectedNextHops: selectedNextHops,
remainingNextHops: remainingNextHops
});
Update: Here is my handleChange Method ->
handleChange(type, event) {
let selectedNextHops = JSON.parse(JSON.stringify(this.state.selectedNextHops));
let remainingNextHops = [];
if(type === 'nexthop') {
selectedNextHops = selectedNextHops.filter(nh => nh !== '');
isContentChanged = true;
if(selectedNextHops.indexOf(event.target.value) === -1) {
selectedNextHops.push(event.target.value);
}
remainingNextHops = this.props.nextHopSapds.filter(nextHop => selectedNextHops.indexOf(nextHop) === -1);
if(remainingNextHops.length !== 0) {
selectedNextHops.push('');
}
this.setState({
selectedNextHops: selectedNextHops,
remainingNextHops: remainingNextHops
});
}
}
The state is updating fine, but the textfield does not display the selected value. I have tried everything I knew. Any help is appreciated.

This is hard to debug without seeing a working snippet or the state ( especially this.state.selectedNextHops) , but based on the code sandbox provided ( in the comment ) , I assume it's the same problem, so this answer will apply to the sandbox code :
this.setState({
selectedID: event.target.value.id,
visibleValue: event.target.value.name
});
event.target.value.id and event.target.value.name are undefined,
console.log(console.log(event.target)) // {value: "S0002", name: undefined}
For the select to display a selected option, the value attribute for both need to match :
<select value="2">
^^^^^^^^^
<option value="1">first value</option>
<option value="2">second value</option>
^^^^^^^^^
</select>
in the example in the code sandbox, the value of the Select is value={this.state.visibleValue} and the values of the options are value={x.label}
Since this.state.visibleValue is always undefined, you'll never see the value of the select update.
A quick fix for this is to change the handleChage function to :
handleChangeTest = event => {
this.setState({
selectedID: event.target.id,
visibleValue: event.target.value
});
};
but that will leave selectedID undefined , to set it, add the attribute id={x.id} to the option and use event.currentTarget to get its value :
{this.state.data.map(x => (
<MenuItem key={x.id} value={x.label} id={x.id}>
^^^^^^^^^
{x.name}
</MenuItem>
))}
And
handleChangeTest = event => {
this.setState({
selectedID: event.currentTarget.id,
^^^^^^^^^^^^^^^^^^^^^^
visibleValue: event.target.value
});
};
Working SandBox

So you try to access the key with e.target.value.id but the target object has only the value and not the id itself. That is why it is undefined after you call the handleChange method. There is a way to access the key though:
The callback does not only pass the event but also the child object as second parameter and this can be used to get the key like this:
handleChangeTest = (event, child) => {
this.setState({
selectedID: child.key,
visibleValue: event.target.value
});
};
This will set the key as selectedID and the value of the selected item as visibleValue.

Related

#material-ui Autocomplete: set input value programmatically

I have an asynchronous Autocomplete component that works fine so far.
Hopefully the simplified code is understandable enough:
export function AsyncAutocomplete<T>(props: AsyncAutocompleteProps<T>) {
const [open, setOpen] = useState(false);
const [options, setOptions] = useState<T[]>();
const onSearch = (search: string) => {
fetchOptions(search).then(setOptions);
};
return (
<Autocomplete<T>
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
onChange={(event, value) => {
props.onChange(value as T);
}}
getOptionSelected={props.getOptionSelected}
getOptionLabel={props.getOptionLabel}
options={options}
value={(props.value as NonNullable<T>) || undefined}
renderInput={(params) => (
<TextField
{...params}
onChange={(event) => onSearch(event.currentTarget.value)}
/>
)}
/>
);
}
The component above works easily: when the user clicks on the input, the Autocomplete component displays an empty input field where the user can type in a value to search for. After the input has changed, the options are refetched to show matching results.
Now I want to add support for shortcodes: when the user types qq, the search term should be replaced by something, just like if the user would have typed something himself.
However, I found no way to update the value of the rendered TextField programmatically. Even if I set value directly on the TextField, it won't show my value but only the users input.
So, any ideas how to solve this problem?
Thank you very much.
What I've tried so far was to simply update the input within onKeyUp:
// ...
renderInput={(params) => (
<TextInput
{...params}
label={props.label}
onChange={(event) => onSearchChange(event.currentTarget.value)}
InputProps={{
...params.InputProps,
onKeyUp: (event) => {
const value = event.currentTarget.value;
if(value === 'qq') {
event.currentTarget.value = 'something';
}
},
}}
/>
)}
With the code above I can see the something for a short time, but it gets replaced by the initial user input very soon.
Autocomplete is useful for setting the value of a single-line textbox in one of two types of scenarios: combobox and free solo.
combobox - The value for the textbox must be chosen from a predefined set.
You are using it so it not allowing you to add free text (onblur it replaced)
Answer: To take control of get and set value programmatically.
you need a state variable.
Check here codesandbox code sample taken from official doc
Your code with my comment:-
export function AsyncAutocomplete<T>(props: AsyncAutocompleteProps<T>) {
... //code removed for brevity
//This is a state variable to get and set text value programmatically.
const [value, setValue] = React.useState({name: (props.value as NonNullable<T>) || undefined});
return (
<Autocomplete<T>
... //code removed for brevity
//set value
value={value}
//get value
onChange={(event, newValue) => setValue(newValue)}
renderInput={(params) => (
<TextInput
{...params}
label={props.label}
onChange={(event) => onSearchChange(event.currentTarget.value)}
InputProps={{
...params.InputProps,
onKeyUp: (event) => {
//get value
const value = event.currentTarget.value;
//if qq then set 'something'
if (value === "qq") {
setValue({ name: "something" });
}
//otherwise set user free input text
else {
setValue({ name: value });
}
},
}}
/>
)}
/>
);
}

Hide/Remove "Create New" menu in react-select

i am using creatable select where i want to hide "create new" menu option. here is my
CodeSandbox i tried following but no luck promptTextCreator={() => false}
thanks you and appreciate any help
// try this way
return (
<CreatableSelect
isClearable
onChange={this.handleChange}
onInputChange={this.handleInputChange}
options={colourOptions}
noOptionsMessage={() => null}
// isValidNewOption={() => true}
// or `isValidNewOption={() => false}`
promptTextCreator={() => false}
/>
);
If you want to hide the create new value message at all times while still being able to create new values, you have to use the prop formatCreateLabel as follows formatCreateLabel={() => undefined} when you define your CreatableSelect.
Disabling create label via formatCreateLabel={() => undefined} is the right direction but the menu list sill shows empty space instead of not showing at all which is what you may prefer.
You may want to hide the menu list completely when there is no option by setting the menu list display to none
// Remember to define a unique id for your component in the constructor
// so you can target the right menu list element to hide it
id = "";
constructor(props) {
super(props);
this.id = "react-select_" + Math.random().toFixed(8).slice(2);
}
handleInputChange = (inputValue: any, actionMeta: any) => {
setTimeout(() => {
const menuEl = document.querySelector(`#${this.id} [class*="-menu"]`);
const menuListEl = document.querySelector(
`#${this.id} [class*="MenuList"]`
);
if (
menuListEl.children.length === 1 &&
menuListEl.children[0].innerHTML === ""
) {
menuEl.style.display = "none";
} else {
menuEl.style.display = "block";
}
});
};
...
<CreatableSelect
id={this.id}
onInputChange={this.handleInputChange}
formatCreateLabel={() => undefined}
...
/>
Live Demo
Just add these props:
menuIsOpen={false} and components={{ DropdownIndicator: null }}
Then handle onKeyDown and onInputChange event as explained in => https://react-select.com/creatable, have a look into "Multi-select text input" section
Here is the complete example:
import React, { Component } from 'react';
import CreatableSelect from 'react-select/creatable';
const components = {
DropdownIndicator: null,
};
const createOption = (label: string) => ({
label,
value: label,
});
export default class CreatableInputOnly extends Component<*, State> {
state = {
inputValue: '',
value: [],
};
handleChange = (value: any, actionMeta: any) => {
this.setState({ value });
};
handleInputChange = (inputValue: string) => {
this.setState({ inputValue });
};
handleKeyDown = (event: SyntheticKeyboardEvent<HTMLElement>) => {
const { inputValue, value } = this.state;
if (!inputValue) return;
switch (event.key) {
case 'Enter':
case 'Tab':
this.setState({
inputValue: '',
value: [...value, createOption(inputValue)],
});
event.preventDefault();
}
};
render() {
const { inputValue, value } = this.state;
return (
<CreatableSelect
components={components}
inputValue={inputValue}
isClearable
isMulti
menuIsOpen={false}
onChange={this.handleChange}
onInputChange={this.handleInputChange}
onKeyDown={this.handleKeyDown}
placeholder="Type something and press enter..."
value={value}
/>
);
}
}
Just add
<CreatableSelect
components={{
...components,
Menu: () => null
}}
/>
Just treat all the new options as invalid, it will show "No options" message:
<CreatableSelect isValidNewOption={() => false}/>
You may want to show "Create" option to user but if element exists or any other reason the "Create" option should be hidden.
For exp:
options=[
{label:"A - 1",value:"A"},
{label:"B - 1",value:"B"}
{label:"C - 1",value:"C"}
{label:"D - 1",value:"D"}
]
In my case, user can only Create A, B, C, D but i have formatted their input to make the label look as "A - 1" , "B - 1" and so on. Now if user again enters A, or B or C or D, it will not match with "A - 1", or "B - 1" or "C - 1" or "D - 1" respectively, in this case i want to hide "Create" option because I am already accepting that value but with different format.
So my logic should go as
<CreatableSelect
name="options"
options={options}
placeholder="Select or Create"
isSearchable
onChange={(option) => appendLabel(option.value)}
value={null}
isValidNewOption={(inputValue)=>
(options.filter((lab)=>lab?.label?.split(" — ")
[0].trim().toLowerCase()===inputValue.toLowerCase()).length>0?false:`Create ${inputValue}`}
/>

Material ui color picker for react value validation message

I am using material ui color picker: https://www.npmjs.com/package/material-ui-color-picker
<ColorPicker
name='color'
defaultValue='#000'
// value={this.state.color} - for controlled component
onChange={color => console.log(color)}
/>
Is there any value validation? If user entered wrong value? How can I show error message?
I searched but could not find anything.
Use color check manually. Define function
const isColor = (strColor) => {
const s = new Option().style;
s.color = strColor;
return s.color !== '';
}
then check before value set
value={isColor(this.state.color)? this.state.color : '#000000'}
can check onChange too
onChange={
color => {
if (isColor(color)) {
console.log(color);
} else {
console.error('Invalid Color');
this.setState({color: '#000000'});
}
};
}
I did custom validation message and seems it's working:
colorChanged = (value, type) => {
var isHex = /^#[0-9A-F]{6}$/i.test(value);
if (value && value.length > 0 && !isHex) {
this.setState({ [type]: true });
} else {
this.setState({ [type]: false });
}
};
<Field fullWidth
type="color"
name="textColor"
id="textColor"
label="Text Color"
onChange={(val) => this.colorChanged(val, 'textColor')}
component={FieldWrapper} />
{this.state.textColor && <Typography color="error" className="error-color">Please enter correct Color!</Typography>}

How to update state with data from a find() method based on value passed from a select drop down

I want to populate item category drop down such that when item name is selected from Item name dropdown, the item id is passed to find the current item from a list of items held in state. This is triggered in an onChange event handler called handleSelectedItem. In the handleSelectedItem handler I try to set the state of item to the current item or newItem found, as shown in code my code sample below.
The problem is after I set the state or so it seems and try to map through the item in state to populate the category option list, I get an error "item.map is not a function".
Please help me solve this issue.
I have tried looking up online for similar issues and how to fix but to no avail.
class Inventory extends Component {
state = {
items: [],
item: [],
pagination: {},
loading: false
};
handleItemSelect = (itemId) => {
const Items = this.state.items;
let item = this.state.item;
let newItem = [];
newItem = Items.find(itemById => itemById._id === itemId);
this.setState({
item: newItem
});
console.log(itemId);
console.log(item);
};
fetchItems = () => {
this.setState({ loading: true });
fetch(`http://localhost:5000/api/items`, { method: "GET" })
.then(response => response.json())
.then(items => {
// console.log(items, items.length);
const pagination = { ...this.state.pagination };
//Read total count from server
pagination.total = items.length;
this.setState({ loading: false, items: items, pagination });
})
.catch(err => console.log(err));
};
componentDidMount() {
this.fetchItems();
}
render() {
const topColResponsiveProps = {
xs: 24,
sm: 12,
md: 12,
lg: 12,
xl: 6
};
const { items, item } = this.state;
return (
<React.Fragment>
<h2>Inventory - [Receive Stock]</h2>
<Row type="flex" justify="space-around">
<Column {...topColResponsiveProps}>
<Card title="Item Details">
<FormItem label="Item Name:">
<Select
showSearch
style={{ width: "100%" }}
placeholder="Select Item"
optionFilterProp="children"
onChange={this.handleItemSelect}
filterOption={(input, option) =>
option.props.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{items.map(item => (
<Option key={item._id} value={item._id}>
{item.item_name}
</Option>
))}
</Select>
</FormItem>
<FormItem label="Category:">
<Select
showSearch
style={{ width: "100%" }}
placeholder="Select category"
optionFilterProp="children"
filterOption={(input, option) =>
option.props.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{item.map(itemCat => (
<Option key={itemCat._id}>{itemCat.category_name}</Option>
))}
</Select>
</FormItem>
</Card>
</Column>
</Row>
</React.Fragment>
);
I expect to update the value of item:[] in state to the value the newItem, so I can map through to populate the category option list.
You expect item to be an array, and yet you are setting it to be an object (find returns the item in the array, not an array itself):
newItem = Items.find(itemById => itemById._id === itemId);
// newItem here is whatever object was returned by `find`
this.setState({
item: newItem,
});
// this.state.item is now an object, and you can't `.map` an object
So, you should either wrap the newItem in an array:
this.setState({
item: [newItem],
});
Or, since item probably shouldn't be an array to begin with since it's just a single item, just don't try to map over it.
I think the problem is you’re using find() function which returns the first element that matches itemById._id, so it drops and error, yuo can check making a log of item right on top inside render function, you should use filter() instead which returns an array.

Keep Semantic-React multiple selection dropdown open when removing an item

I'm trying to keep the multiple selection dropdown available from Semanti-UI-React open when I remove a selected item, but still have it close onBlur. I can set closeOnBlur to false and I get the behavior I want for removing the selected item, but then I have to click the arrow on the dropdown to close it. I tried plugging into the relevant events to see if there was a way I could achieve the desired behavior manually, but oddly enough if closeOnBlur is set to false, I don't even get the onBlur event.
Here is my code:
<Dropdown
style={{whiteSpace: 'nowrap', zIndex: 9999}}
upward={true}
search={true}
multiple={true}
selection={true}
loading={loading}
options={options}
value={this.props.selectedCodes || []}
closeOnBlur={false}
onBlur={() => console.log('onBlur')}
onChange={ (e, d) => {
console.log('onChange');
const value = d.value as string[];
const displayValues = value.map(code => {
const lookupEntry = options.find(i => i.value === code);
return lookupEntry ? lookupEntry.text : '';
});
const displayValue = displayValues.reduce(
(result, text) => {
return `${result}, ${text}`;
}, ''\
);
this.props.onSelectionChange(value, displayValue);
}}
onClose={() => console.log('onClose')}
/>
Any suggestions on how to achieve my desired behavior, or insight as to why the onBlur even doesn't fire if closeOnBlur is set to false?
This component supports manual control over it's open/closed status view an open prop. So simply manage that prop via the state of your custom containing class;
getInitialState() {
return { open: false };
},
handleClose() {
this.setState({open: false});
},
handleOpen() {
this.setState({open: true});
}
render() {
return <Dropdown
open={this.state.open}
onBlur={this.handleClose}
onFocus={this.handleOpen}
...
/>;

Resources