Clear React Widget DropdownList if not select any item - reactjs

I'm using React Widgets for the Dropdown List, I want to customize the onChange to get my state as the selected value:
const { selected } = this.state;
return <DropdownList {...rest}
data={fitData} onSearch={this.search}
onChange={this.change}
/>
The onChange simply like this:
change(selected) {
this.setState({selected});
}
It works, but when I close the dropdown list without selecting any value, the selected still chosen. What could I do to remove the selected if I don't choose any value?

The onChange event will get called only on a value change.
if you want to listen to the 'closed without selecting' You should listen to the onToggle event.
You can call the same method as you did on the onChange and check the selected value is null/undefined.
onToggle={this.change}

Related

React-select onChange trigger when user select same option

The onChange of a react-select drop down is getting triggered when I select an already selected value in the drop down. Is there a way to configure react-select to not trigger onChange event if already selected value is selected again.
handleOnChange(value) {
console.log("test");
this.setState({ multiValue: value });
}
render() {
return (
<div>
<Select.Creatable
options={this.state.options}
onChange={this.handleOnChange.bind(this)}
value={this.state.multiValue}
showNewOptionAtTop={false}
/>
</div>
);
}
As you can see the console log calling even if the value is the same. Codesandbox
You can control the value on onChange of react select.
I changed your onChange function with arrow function:
onChange={value => {
if (value !== this.state.multiValue){
this.handleOnChange(value);
}
}}
codesandbox
I'm not sure whether you can disable the change event but as a workaround You can simply hold the current value of the selected item and return from the change handler if the selected item was the previous one like #ahmetkilinc answer, also menu items have an option
isDisabled
that you can change to true when one item is selected, therefore it can't be selected anymore.

How to determine if user is scrolling through choices of Material-UI Autocomplete with arrow keys?

I have a material UI autocomplete component in a ReactJS application which I desire to have the following behavior:
The user can type input into the autocomplete, and when the user presses enter without scrolling through the suggested choices, event A is fired with the input typed in the autocomplete as a parameter.
The user can scroll through the suggested choices (with arrow keys), and when the user presses enter, event B is fired with the currently selected autocomplete choice in the parameter
The user can scroll through the suggested choices (with arrow keys/mouse scroller), and when the user clicks one of the suggestions, event B is fired with the clicked autocomplete choice in the parameter
I was able to make these behaviors individually. I handled the first behavior with an onKeyDown waiting for an enter key, and the second + third behavior with an onChange as suggested here:
stackoverflow.com/questions/58666189/getting-the-value-in-the-react-material-ui-autocomplete.
The problem appears when I put both events together. When I attempt to scroll through the choices with arrow keys and press enter (behavior 2), both the onKeyDown and onChange events get fired. This fires BOTH event A with what the user typed and event B with what the user selected, when I only want to fire event B with what the user selected. Is there a way to detect if the user has begun scrolling through the autocomplete suggestions with arrow keys (so that I can wrap event A in an if condition), or an alternative way to look at this problem to resolve it?
The Autocomplete component:
<Autocomplete options={someArrayOfStrings}
onChange={this.submitComment} // event B
onKeyDown={this.submitCommentEnter} // event A
value={this.state.userInput} // what the user has typed
autoComplete
freeSolo
renderInput={(params) => <TextField {...params}
fullWidth
label="Search"
variant="outlined"/>}/>
Event A (submitCommentEnter):
submitCommentEnter(e) {
if (e.key == 'Enter') { // possibly add check if user is scrolling through autocomplete with arrow keys here?
/* content of event A here; uses this.state.userInput */
}
}
Event B (submitComment):
submitComment(event, value) {
if (value !== null) {
/* content of event B here; uses value */
}
}
You don't need to handle the keyDown event, You just need to use the reason of on-change event as per document onChange provide three params
onChange={(event, value, reason) => {
console.log("onChange", reason, value, event.currentTarget);
}}
The reason can be of 5 types "create-option", "select-option", "remove-option", "blur" or "clear". when you press enter in text field reason will be create-option and when you select an option from the drop-down the reason will be select-options, below is the complete code to verify the fact.
import React from "react";
import TextField from "#material-ui/core/TextField";
import Autocomplete from "#material-ui/lab/Autocomplete";
const someArrayOfStrings = ["test", "test2", "test3"];
export default function CheckboxesTags() {
const [selectedValues, setSelectedValues] = React.useState();
return (
<React.Fragment>
<Autocomplete
options={someArrayOfStrings}
onChange={(event, value, reason) => {
console.log("onChange", reason, value, event.currentTarget);
// setSelectedValues(value);
}}
value={selectedValues} // what the user has typed
autoComplete
freeSolo
renderInput={params => (
<TextField {...params} fullWidth label="Search" variant="outlined" />
)}
/>
</React.Fragment>
);
}
I have also created this code-sandbox project, where you can check the console for

How can I disable checkbox for multi value selection in react-dropdown-tree-select?

I am new to React and I stumbled upon react-dropdown-tree-select for a specific need I had allowing users to view data in Tree format for selection in DropDown. But, I want the users to only select 1 value at a time. How can i enforce that?
There is no such property available directly in react-dropdown-tree-select. But you can listen to onChange event and reset the entire data which you have passed in data props with the updated data with only one node selected.
Check the following code.
onChange = (currentNode) => {
// keep reference of default data structure.
const updatedData = this.props.defaultData;
// find node related to currentData in your tree and set checked property
this.setState({data : updatedData });
}
render = () => {
return (
<DropdownTreeSelect
data={this.state.data}
onChange={this.onChange}
/>
);
}
This will basically stop the user from selecting multiple options instead of disabling remainig item you are unselecting the previously selected items.
If you just want one element selected at a time you can use mode="radioSelect"

React semantic-ui Dropdown onChange not working

Here's the code:
class MenuContainerComponent extends Component {
onInputWidgetMenuChange(event, data) {
console.log(data);
}
render() {
var inputWidgets = [];
for (var i = 0; i < this.props.cdata.widgets.inputWidgets.length; i++) {
var componentName = getComponentNameFromType(this.props.cdata.widgets.inputWidgets[i]);
var key = "inputWidget" + i;
inputWidgets.push(<Dropdown.Item key={key}>{componentName}</Dropdown.Item>);
}
return (
<Dropdown style={childStyle} text='Input widgets' icon='keyboard' floating labeled button className='icon' onChange={this.onInputWidgetMenuChange}>
<Dropdown.Menu>
<Dropdown.Header icon='tags' content='Select a widget to add to canvas' />
<Dropdown.Divider />
{inputWidgets}
</Dropdown.Menu>
</Dropdown>
)
}
I am trying to get an event on menu selection. 'onClick' is working in similar fashion but there is no event on menu selection.
AFAIK, since you're using Dropdown.Menu inside this Dropdown, the onChange won't work. It's for normal Drodowns (like selecting a value etc). Try creating a generic onClick and assign it to <Dropdown.Item />
Giri's answer is correct. Change this line
inputWidgets.push(<Dropdown.Item key={key}>{componentName}</Dropdown.Item>);
to
inputWidgets.push(<Dropdown.Item key={key} value={componentId} onClick={this.onInputWidgetMenuChange}>{componentName}</Dropdown.Item>);
Where componentId is the actual value of the Dropdown.Item, (as opposed to the text displayed). Given the right circumstances componentId can be the same as the componentName too.
Another thing is that since you're using Dropdown.Menu inside the Dropdown, clicking the items on the menu won't automatically change the value of the Dropdown. (which is why the onChange of event the Dropdown component isn't fired). You need to save the current value of the Dropdown in the react state and manually set the trigger prop of Dropdown to make it look like the selected item.

React Radio Button event on "checked" attribute

I'm trying to handle an event based on the 'checked' attribute of a radio button in React.js. I want the buttons to allow for selecting more than one value, so I removed the 'name' attribute which seemed to disallow multiple selections.
The base radio button component looks like
export function Radio_Button_Multiple_Selection (props) {
return (
<label>
<input type="radio"
checked={props.form_data[props.field_name].indexOf(props.btn_value) > -1}
onClick={props.radio_effect} />
{props.btn_value}
</label>
)
}
I have a form_data objec that has an array of values that correspond to the btn_value of the radio buttons, where if the value is found in the array it should come up as checked. (And this part is working fine right now, they do in fact show up checked as expected):
const form_data = {
...
occupations: ['student', 'merchant', 'paladin', 'troll'],
...
}
Now, I also have a react class with a method for manipulating the values in the occupations array,responding to whether the radio button being licked was already checked or not:
handleRadioButton (event) {
const target = event.target;
const value = target.value;
const isChecked = target.checked;
console.log(isChecked) // this undefined. why?!?
if (isChecked) {
// remove it from array
// etc.
} else {
// add it to array
// etc.
}
}
My main issue is that following:
When I console.log the "checked" logic that returns a boolean inside the RadioButton component's checked attribute, it comes up as expected (true of false if it is or isnt in the array). But it always comes up as checked = undefined in the class method for handling the buttons.
You cannot uncheck a radio button in HTML either. You have to control the checked attribute with your props or state:
Even more, you should rely only on your state, instead of a mix, e.target.checked & state.
class Radio extends Component {
state = {}
render() {
return <input
type="radio"
checked={this.state.checked}
onClick={e => this.setState({
checked: !this.state.checked
})}
/>
}
}
<input type="radio" />
I found the workaround:
use the 'value' attribute to store the same information that I am storing under the 'checked' attribute, with an array that has the button's value AND the checked logic boolean; e.g., value=[boolean, btn_value]
then access the 'value' attribute in the event handler. the value arrives as a full string, so I just split it at the comma and work from there.
it's hacky, but it worked.

Resources