How to change initialValue dynamically inside getfielddecorator antd? - reactjs

I want to change initial value of select when ever user selects option.
To be more precise, I have many options to select and by default I want display "All" and whenever user selects another option(s) "All" option should disappear.
What I have done : I have tried to render initialValue conitionally whenever user selects option
<Form.Item label="Компьютеры">
{getFieldDecorator("computers", {
initialValue: this.props.status ? null : "All",
})(
<Select
mode="multiple"
onChange={this.handleCompChange}
>
{this.props.comps.map(comp => (
<Option value={comp.key} key={comp.key}>
{comp.name}
</Option>
))}
</Select>
)}
</Form.Item>

You can't dynamically change the initialValue unless your unmount the Form.Item.

Related

Set conditional defautlValue antd

I want to set a default value (reason) on the dropdown that depends wether refundDateInput inputs has been filled.
What I currently have is:
A watch to get refundDateInput:
const refundDateInput = Form.useWatch('refundDate', form);
A conditional initialValue that depends on refundDateInput:
<Form
layout="vertical"
form={form}
onFinish={submit}
initialValues={{
reason: refundDateInput && refund,
}}
onValuesChange={() => {
validate();
}}
>
And then the actual dropdown:
<Select
disabled={watchInputFields()}
data-testid="select-reason-id"
placeholder="Select"
className={styles.fullWidth}
allowClear
dropdownMatchSelectWidth={false}
>
{Object.keys(Reason).map((key) => (
<Option data-testid="select-option-id" key={key} value={key}>
{Reason[key]}
</Option>
))}
</Select>
The conditional initalValue is not doing anything cause, well, is not initial anymore.
I need that reason to be selected if refundDate is been filled, but also, be able to change to another reason if necessary.

select dropdown option set to default when click reset button on react js

I am working on a dropdown select filter and there is a reset button, so I want to reset data whenever I click on it.
this is my select dropdown where I am filtering data
<select
className={style.input}
name="categoryId"
onChange={e => handleCategory(e.target.value)}
>
<option value="" disabled selected>
Select A Categtory
</option>
{props.category_list && props.category_list.length > 0
? props.category_list.map((item, index) => (
<option value={item.categoryId}>{item.categoryName}</option>
))
: null}
</select>
this is onChange method of select
const handleCategory = (value) => {
setErrorMsg(null);
setCategoryID(value);
props.getSubCategoryList(value);
};
and this is a reset button, I tried to make
const handleReset = (value) => {
setReset(true);
setCategoryID('');
setSkillID('');
setLocationId('');
props.getSubCategoryList(1);
};
but the problem is when I click on reset it resets, but the value doesn't change to default one in options also if I change it in {item.categoryName} then three same values appear under options. hope this information is enough.
You need to bind the selected value to select element.
Provide categoryID as a prop to your component.
Set it as the value property of select.
<select
...
...
value={props.categoryID}
onChange={e => handleCategory(e.target.value)}
></select>

React Select Dropdown disable individual options not working

I am fairly new to react, but I am trying to create a dropdown with ant-design with some of the individual options disabled based on certain IDs.All the ID data returns as expected, however, the disable logic (which I think should work) in the disable attribute seems to disable every option in the dropdown. Anyone know what could be going on?
<Select
value={this.props.value}
name={this.props.name}
className={this.props.cssClass}
disabled={this.props.disabled}
onChange={this.props.onChange}
mode="multiple"
showSearch
filterOption={(input, option) => option.props.children.toLowerCase()
.indexOf(input.toLowerCase()) >= 0}
size="large"
>
{
this.state.data.map(opt => (
<Option
disabled={this.props.multiSelect.filter(data => data.DivisionId !== opt.Id)}
key={opt.Id}
value={opt.Id}
>
{opt.Name}
</Option>
))
}
</Select>
Issue with your code is that array filter method will always return true because empty array is parsed as true.
Replace filter method with find method.

setting default-value in react select dropdown

I am trying to set a default value in my select tag so that on every onChange event I can call an API which is my requirement.
I searched online on how to set defaultvalue for select tag, people suggested to use defaultValue attribute which did not work for me.
let serviceProviderLocationNames = this.props.serviceProviderLocationName.map((location, key) => {
return <option key={key} value={location.SERVICE_PROVIDER_LOCATION_ID}>{location.DESCRIPTION}</option>
});
<select
defaultValue = {{ label: "Select", value: 0}}
name="serviceProviderLocationDropDown"
onChange={this.updateServiceProviderLocationId}
>
{serviceProviderLocationNames}
</select>
I expected to see a "select" value as default and others to be the values that I got from an API, but I couldn't see the "select"
Try using the defaultValue parameter.
<Select
name="form-dept-select"
options={depts}
defaultValue={{ label: "Select Dept", value: 0 }}
onChange={e => {
this.setState({
department: e.label,
deptId: e.value
});
}}
/>
To see Select by default, you need to add an option before your original option as,
<select
value={this.state.selectedValue} //Add the selected value here, may be from state. For example `this.state.selectedValue` you can change the name whatever you have
name="serviceProviderLocationDropDown"
onChange={this.updateServiceProviderLocationId}
>
<option>Select</option> //By default selected
{serviceProviderLocationNames}
</select>
onChange of your select you have updateServiceProviderLocationId function, and you might set selected value in state, you need to write that in value prop above so that it will become a controlled component.
Demo
I think you need to brush up html element basics here. So to select value in dropdown by default you need to add selected to html tag and that should take care of default selected item.
So you need to add login to select the element in the option and while change you should be able to get default value
let serviceProviderLocationNames = this.props.serviceProviderLocationName.map((location, key) => {
return <option
key={key}
value={location.SERVICE_PROVIDER_LOCATION_ID}
selected={key=== PUT_INDEX_TO_BE_DEFAULT_SELECTED}
>
{location.DESCRIPTION}
</option>
});

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

SCENARIO A user has a dropdown and he selects an option. I want to display that dropdown and make that option a default value which was selected by that user last time.
I am using selected attribute on option but React generates a warning asking me to use default value on select.
For e.g.
render: function() {
let option_id = [0, 1];
let options = [{name: 'a'}, {name: 'b'}];
let selectedOptionId = 0
return (
<select defaultValue={selectedOptionId}>
{option_id.map(id =>
<option key={id} value={id}>{options[id].name}</option>
)}
</select>
)
}
});
Problem is that I don't know the selectedOptionId as the selected option could be any option. How would I find the defaultValue ?
React uses value instead of selected for consistency across the form components. You can use defaultValue to set an initial value. If you're controlling the value, you should set value as well. If not, do not set value and instead handle the onChange event to react to user action.
Note that value and defaultValue should match the value of the option.
In an instance where you want to set a placeholder and not have a default value be selected, you can use this option.
<select defaultValue={'DEFAULT'} >
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
Here the user is forced to pick an option!
EDIT
If this is a controlled component
In this case unfortunately you will have to use both defaultValue and value violating React a bit. This is because react by semantics does not allow setting a disabled value as active.
function TheSelectComponent(props){
let currentValue = props.curentValue || "DEFAULT";
return(
<select value={currentValue} defaultValue={'DEFAULT'} onChange={props.onChange}>
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
)
}
What you could do is have the selected attribute on the <select> tag be an attribute of this.state that you set in the constructor. That way, the initial value you set (the default) and when the dropdown changes you need to change your state.
constructor(){
this.state = {
selectedId: selectedOptionId
}
}
dropdownChanged(e){
this.setState({selectedId: e.target.value});
}
render(){
return(
<select value={this.selectedId} onChange={this.dropdownChanged.bind(this)}>
{option_id.map(id =>
<option key={id} value={id}>{options[id].name}</option>
)}
</select>
);
}
Thank you all for this thread! My colleague and I just discovered that the default_value property is a Constant, not a Variable.
In other React forms I've built, the default value for a Select was preset in an associated Context. So the first time the Select was rendered, default_value was set to the correct value.
But in my latest React form (a small modal), I'm passing the values for the form as props and then using a useEffect to populate the associated Context. So the FIRST time the Select is rendered, default_value is set to null. Then when the Context is populated and the Select is supposed to be re-rendered, default_value cannot be changed and thus the initial default value is not set.
The solution was ultimately simple: Use the value property instead. But figuring out why default_value didn't work like it did with my other forms took some time.
I'm posting this to help others in the community.
Use defaultValue and onChange like this
const [myValue, setMyValue] = useState('');
<select onChange={(e) => setMyValue(e.target.value)} defaultValue={props.myprop}>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
Example
https://codesandbox.io/s/priceless-lamarr-fetpr?file=/src/App.js
With Hooks and useState
Use defaultValue to select the default value.
const statusOptions = [
{ value: 1, label: 'Publish' },
{ value: 0, label: 'Unpublish' }
];
const [statusValue, setStatusValue] = useState('');
const handleStatusChange = e => {
setStatusValue(e.value);
}
return(
<>
<Select options={statusOptions}
defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]}
onChange={handleStatusChange}
value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)
A simple solution to set the value without using selected in option,
follow these steps:
Default the value to 0 [which I am not considering it as a value to be in use] to x-column
Refer the image
4 steps
set the "IntialValue" of the x-column : 0 to the
use the same string used in your [selected] and set it here with the if condition and when found, mark the "values.x-column = 0"
Remove the "selected" and other items set [if any] in tag
4.finally set this condition
now navigate , the value in the column is defaulted to the one which is marked in step-2 / that you wanted to be set in selected
I have tried and its working for me
A small correction.. line 45 in image.. read the column as column_value_id
I tried different options to avoid console errors the following option worked with selected option without errors in console:
{const [myValue, setMyValue] = useState('');
const changeHandler = (e) => {
setMyValue(e.target.value);
};
<select id="select" value={myValue} onChange={changeHandler}>
{!myValue&& <option value="">choise from list</option>}
{elementsArr.map((el) => {
return (
<option key={el.id} value={el.name}>
{el.name}</option>
);
})
</select>}

Resources