setting default-value in react select dropdown - reactjs

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>
});

Related

How to update div in dom with react

I have this select in a react component
<Select defaultValue="" style={{ width: 200 }} onChange={handleChange}>
<OptGroup label={correctGroup[0].Tag}>
<Option value={correctGroup[0].Text}>{correctGroup[0].Text}</Option>
<Option value={correctGroup[1].Text}>{correctGroup[1].Text}</Option>
<Option value={correctGroup[2].Text}>{correctGroup[2].Text}</Option>
</OptGroup>
<OptGroup label={wordForSelect[0].Tag}>
<Option value={wordForSelect[0].Text}>{wordForSelect[0].Text}</Option>
<Option value={wordForSelect[1].Text}>{wordForSelect[1].Text}</Option>
<Option value={wordForSelect[2].Text}>{wordForSelect[2].Text}</Option>
</OptGroup>
</Select>
Once it gets rendered it's a bunch of divs. I should also mention I'm using antd. When a user selects an option the onChange above is fired and I can see the text that was chosen.
Now based on the text I either want to make the background green or red.
So in the onchange do I use the old school document.getElementByClass to change the background. The selected item gets placed as text in an element that has a class name of "ant-select-selection-item". But since this is generated dynamically by antd I can't use useRef...
So how can I add and remove a class name from a div with the class name "ant-select-selection-item" ?
const handleChange = (value: string, defaultOptionType: any) => {
//??
};
can't you use the style prop of the option?
And you can store the style in the state. Something like this.
https://codesandbox.io/s/select-with-search-field-antd-4-22-8-forked-yt1j6e?file=/demo.js:949-954
I'm not sure if I understood the question. But one solution could be to capture the option value and then filter over all the HTML select options to find the selected option and then add a class to it.
const handleChange = (value) => {
// Get the selected option value
const selectedValue = value.target.value || null;
// Check taht there is a value
if (selectedValue) {
// Find the selected option element by the selected value
const currentOption = [...value.target.options].filter((o) => o.value === selectedValue)
// If there was a match add a class to the option
if (currentOption.length > 0) {
currentOption[0].classList.add("red");
}
}
};

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>

How to change initialValue dynamically inside getfielddecorator antd?

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.

how to open a textfield and set its value on select some value in dropdown in react

I am trying to display a textbox based on some selected value in dropdown in react.
my code is
<label>
color:
<select value="Radish" onChange ={this.checkColor}>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<input type="text" name="project Id" id="project Id" style={{display:'none'}}/>
<label>
Onchange, the below function will be invoked.
CheckLayers(evt){
if(evt.target.value === 'Orange'){
this.setState({showField:true})
}
}
But I am not able to see the textbox. I tried to put condition based on showField but that's not working.
(this.state.showField)
<input type="text" name="project Id" id="project Id" style={{display:'none'}}/>
Please advice!!
There are a few things to check in your code.
First, with your current implementation of the <select> and <option> elements, the actual value on the <select> will never change because it is always set to "Orange". You need to also save the last selected <select> value in your component's state:
checkLayers(event) {
const { value } = event.target;
this.setState({
showField: value === "Orange",
selectedValue: value
});
};
And in your render method use the selectedValue accordingly:
render() {
return (
<label>
color
<select value={this.state.selectedValue} onChange={this.checkLayers}>
/* {your options} */
</select>
</label>
);
}
The next thing to check is the checkLayers method. Inside this method you are trying to access this. Since the <select>'s onChange callback is going to be called on a different context as your component (you can check this by logging this inside checkLayers). As a result of this, you need to bind the checkLayers method to your component's context. This can be done by explicitly binding the function when passing it as a callback or by defining the class method as an arrow function.
Binding option (in the render method):
<select value={selectedValue} onChange={this.checkLayers.bind(this)}>
Class method as Arrow function option:
class MyComponent extends React.Component {
...
checkLayers = (event) => {
const { value } = event.target;
this.setState({
showField: value === "Orange",
selectedValue: value
});
};
...
There is also an alternative option using arrow functions:
<select value={selectedValue} onChange={(event) => this.checkLayers(event)}>
You can learn more about thishere
The last thing to check is how you are trying to conditionally render the <input> element. Right now you are hardcoding the style as { display: 'none' }. You could change this based on the value of showField, but I think is it better only render the <input> when showField is true, like this:
render() {
const { selectedValue, showField } = this.state;
return (
<label>
color:
<select value={selectedValue} onChange={this.checkLayers.bind(this)}>
/* {your options} */
</select>
{showField ? (
<input
type="text"
name="project Id"
id="project Id"
/>
) : null}
</label>
);
}
Here we are using the ternary operator to decide if we render the element or we render nothing (using null).
You can see the final implementation here:
Comment if you have further questions, cheers!

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