How to get text of selected <Dropdown/> option in ReactJS? - reactjs

I am working on a ReactJS application and I am trying to get the text of a selected option in a dropdown (Semantic UI component);
exposedCampaignOnChange = (e, {value}) => {
this.props.campaignExposedSelected(value);
};
<Dropdown
placeholder='Campaign Exposed To'
fluid
search
selection
multiple
options={this.state.campaigns}
onChange={this.exposedCampaignOnChange}
/>
The above code returns the value. this.state.campaigns is made up of an array of objects with value and text properties. In addition to the value, I also want to get the textvalue of the selected options.
Appreciate any guidance on the matter.

You can use synthetic event's target property to get the text like:
exposedCampaignOnChange = (e, {value}) => {
e.persist();
console.log(e.target.textContent);
this.props.campaignExposedSelected(value);
};
<Dropdown
placeholder='Campaign Exposed To'
fluid
search
selection
multiple
options={this.state.campaigns}
onChange={this.exposedCampaignOnChange}
/>

Semantic ui react Dropdown onChange event takes two arguments -
onChange(event: SyntheticEvent, data: object). You don't need to pass them explicitly while calling the function.
exposedCampaignOnChange = (e, value) => {
e.persist();
this.props.campaignExposedSelected(value);
};

data/value should have selected option text like in semantic UI
function getSelectedTextValue() {
alert( $('.ui.dropdown').dropdown('get text') + " : " + $('.ui.dropdown').dropdown('get value') );
}

Related

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"

Clear React Widget DropdownList if not select any item

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}

React Checkbox onCheck get key value

I am currently working on a website I am building with React, and I am not able to get the Checkbox key value from the onChange event. This is what my code looks like:
handleChange = (e) => {
console.log('it works');
console.log(e.target.key);
}
And my Checkbox code:
<Table.Cell><Checkbox key={singleNews.key} name="myCheckBox1" onChange={this.handleChange}/></Table.Cell>
It simply prints out 'it works', and 'undefined'. I have also used 'this.handleChange = this.handleChange.bind(this) in my constructor. Could anyone please help me find out what the error might be? For the record; I am currently using the Semantic UI React framework - could this be the problem?
Thanks in advance.
First of all the key property in react is a special prop that should not be accessed by your app and treated as internal to react
If you are not trying to use the key for anything and instead just trying to get the updated data from this issue thread it should be possible to access the value in your event handler like this:
handleChange = (e, data) => {
console.log('it works');
console.log(data.value);
}
If you want to pass data into your event handler based on data it received when runnning then what you can do is change your Checkbox code to this:
<Table.Cell>
<Checkbox name="myCheckBox1" onChange={(e, data) => this.handleChange(singleNews.key, data.value)}/>
</Table.Cell>
And your change handler to this
handleChange = (key, value) => {
console.log('here\'s the key', key);
console.log('and the value', value);
}
As per the docs of semantic-ui-react (this is the library you are using according to the tags right?) you get 2 parameters: event and data.
The data is:
All props and proposed checked/indeterminate state.
So your code should be something like:
handleChange = (e, data) => {
console.log('it works');
console.log(data); // the data / props that passed to the component
}
Note that key is reserved for react and won't pass back to the handler.
You can use any other prop though.

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