How to get 'name' in event [Autocomplete] component - reactjs

i have handler fn for handle input from Textfield.
I want use it fn for autocomplete component, but i cant get 'name' and value from it.
function handlerChange(e){
const { name, value, checked } = e.target;
return { name, value: value || checked };
}
<Autocomplete
id="distributions"
name="defaultDistr"
options={distributions}
getOptionLabel={distribution => distribution}
inputValue={defaultDistr}
defaultValue={defaultDistr}
onChange={(e, value) => {
console.log('e', e, 'value', value);
}}
renderInput={params => (
<TextField
{...params}
name="defaultDistr"
label="distributions"
margin="normal"
fullWidth
/>
)}
/>

For Autocomplete, there are many different events that can cause changes to the value. There are several different elements from which those events can come from, so you cannot rely on the target of the event to get the name. Similarly the target of the event does not necessarily have a value and even if it does, that value may not represent the current value of the Autocomplete. This is why the correct value is passed as a second parameter to your onChange handler.
Assuming there is more significant code in handlerChange than what you've shown such that it is worth trying to reuse, you can do something like shown below which creates a new object organizing the information into the structure the handler is expecting.
<Autocomplete onChange={(event, value)=> { handlerChange({target: {name: "defaultDistr", value: value}})} .../>

Related

How to get value from React Select Form

Sorry for just a basic question, But I'm a little stuck here to find any way to get values from React Select after making a selection.
This is a Simple Selection setup.
const selectOptions = [
{ value: 'YES', label: 'Set to Active' },
{ value: 'NO', label: 'Set to Mute' }
]
<Label className='form-label'>Select</Label>
<Select
isClearable={false}
className='react-select'
classNamePrefix='select'
options={selectOptions}
theme={selectThemeColors}
/>
I want to get the value against user-selected choice and put it into userChoice content using useState.
const [userChoice, setUserChoice] = useState("")
value can be YES or NO as defined in selectOptions. But how to pass this into userChoice.
I tried using onChange={(e) => setUserChoice(e.target.value)} But this thing is not working.
Also tried onInputChange={handleInputChange} as suggested in previously asked threads on StackOverflow but not working here.
The onChange callback handler gets called with the whole choice object instead of the event object. Therefore it should be like this.
<Select
...
...
onChange={(choice) => setUserChoice(choice)}
/>
If you only intested in YES / NO value, then use,
onChange={(choice) => setUserChoice(choice.value)}

how to get the value the auto complete in the form

I try to get the value of autocomplete in console.log()
it's posible to get the value of autocomplete after selection of title ?
find below code source
https://stackblitz.com/edit/react-tewwbp?file=demo.js
[code source[1]
You are currently using uncontrolled Autocomplete so you don't have access to the value that is currently selected. To console the value you can use something like this:
<Autocomplete
onChange={(event, newValue) => {
console.log(newValue);
// setValue(newValue);
}}
...
/>

react-select not setting defaultValue param properly

So I have this piece of code, and somehow it's not setting the defaultValue properly, here's the value of patchsOptions[0]:
console.log(patchOptions[0]); // Object { value: "10.15.1", label: "10.15.1" }
<Select
className="col-2"
placeholder="Patch"
defaultValue={patchsOptions[0]}
options={patchsOptions}
onChange={option => this.onChangePatch(option.value)}
/>
The default value keeps empty, but the options are loaded correctly, so I didn't see the problem since looking at some examples, it also uses the "options[0]" variable.
By changing the code this way, it works as expected:
<Select
className="col-2"
placeholder="Patch"
defaultValue={{ value: 'test', label: 'test' }}
options={patchsOptions}
onChange={option => this.onChangePatch(option.value)}
/>
They both have the same obj structure, so I didn't get where's the problem. I logged the default value before rendering, and it's setting normally, it's not empty.
As the patchesOptions is set from an Async call, then the first render time it will be null, and the defaultValue doesn't change if you change it's value, this is like an initial value, so what you can do is to use value option, and link it to the selectedPatch, also I did some change (onChange) like this:
<Select
className="col-2"
placeholder="Patch"
value={{this.state.selectedPatch.value, this.state.selectedPatch.label}}
options={patchsOptions}
onChange={option => this.onChangePatch(option)}
/>

Simulate click event in React with TypeScript material-ui

I'm rendering some material-ui TextFields. By manually typing the value inside it, it'll work properly. It is using handleChange() (change) and handleBlur() (autosave) to handle those events. but the scenario is I have to update the value not by manually typing but from the store.
So, if I pass the value from the store, it is not actually updating the value unless I click inside the field and click away or tab out. the value is showing inside the field but not invoking handleChange() and handleBlur() which are the only way to update the value inside. Also I have to type at least a value.
Approach:
I set an onFocus to the field and on it's handleFocus, I'm trying to either simulating click() and blur() or calling handleClick() and handleBlur(). If I simulate a click event,
Uncaught TypeError: element.click is not a function
If I try to call handleChange() and handleBlur()
readonly refO: React.RefObject<HTMLInputElement>;
constructor(props: InputProps) {
super(props);
this.refO = React.createRef<HTMLInputElement>();
}
...
<TextField
autoFocus
inputRef={this.refO}
id={this.labelId}
required={required}
label={label}
error={error}
value={this.setValue()}
onBlur={handleBlur}
onChange={handleChange}
disabled={disabled}
fullWidth
type={type}
InputLabelProps={InputLabelProps}
InputProps={{ className: cx({ [classes.modified]: isModified }) }}
onFocus={this.handleFocus}
/>
What can I do inside handleFocus() in order to achieve this. or the proper approach to achieve this. I'm very new to TypeScript. is my approach wrong or any other way to overcome this.
handleFocus = (element: HTMLInputElement) => {
element.click();
this.props.handleChange();
this.props.handleBlur();
}
PS: cannot add more code due to some sensitivity issues.
solved the issue.
i knew it has to be done from inside the handleFocus. but what i was doing call other event handlers from it. then i thought why should i. the function has been invoked so just update the values from it.
handleFocus = (value) => {
// update my value
}
it's unconventional but all we require is the result.
ps: i even pinged few people on twitter(this has put our reputation on the stake. it was a race against time). i was that desperate. i apolagize to them.

How to get text of selected <Dropdown/> option in 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') );
}

Resources