I'm totally new in react and I am trying to create add/edit form with combo box in it. I saved data in database but now when I loaded the form there is no selected value in "bank" combo. Looks like combo gets default value "Select" and I don't know where is the problem. My .net backend returns proper bank id from database and company.bankId also has value.
interface IProps {
closeAddEditCompanyModal: any,
cancelClick: any,
saveClick: any,
isVisible: boolean,
currentCompany: CompanyModel,
}
interface IState {
company: CompanyModel;
validationMessage: string,
isLoading: boolean,
activeIndex: number;
selectedIndex: number;
banks: Array<BankModel>;
isVisibleAddEditBankDialog: boolean;
}
handleChangeSelect = (key, e) => {
const company: CompanyModel = { ...this.state.company};
company[key] = e.value;
this.setState({ company: { ...company } });
};
<div style={{ minHeight: '50px' }}>
<FormControl>
<InputLabel htmlFor="active-label">Banks</InputLabel>
<Select
name="bankId"
options={this.state.banks.map( bank => ({
value: bank.bankId,
label: bank.bankName
}))}
onChange={(e) => this.handleChangeSelect('bankId', e)}
value={company && company.bankId ? company.bankId : ''}
>
</Select>
</FormControl>
import { useState } from "react";
import Select from "react-select";
function App() {
const [companyId, setCompanyId] = useState();
const letterChange = (data) => {
console.log(data);
company[data.value] = data.value;
// you can do here whatever you wish to do
// setCompanyId(data);
};
const banks = [
{ value: "bank1", label: "bank1" },
{ value: "bank2", label: "bank2" },
{ value: "bank3", label: "bank3" },
{ value: "bank4", label: "bank4" },
{ value: "bank5", label: "bank5" },
{ value: "bank6", label: "bank6" },
{ value: "bank7", label: "bank7" },
];
const company = [{
bank1: { value: "company1", label: "company1" },
bank2: { value: "company2", label: "company2" },
}];
return (
<>
<div className="App">
<Select
name="bankId"
options={banks}
onChange={letterChange}
value={companyId}
></Select>
</div>
</>
);
}
export default App;
I am still not clear what you are trying to achieve here. But here is a small piece of snippet that might help you.
Couple of things that i would like to point out in your code.
Inside your onChange handleChangeSelect you are passing a hardcoded value by passing bankId as string. I don't know if thats intentional.
You don't have to loop through the array inside options. Rather you can just pass the whole array itself.
This is just a suggestion but if you are already using material ui package you can use the select from material ui itself. This is just to avoid using extra packages unless and until there is a need for it.
Related
I want to build a form that can be used to manage an option that is stored in the database as a number.
However, if I now enter the item from the database into the hook:
const form = useForm({.
initialValues: {
option: 1
},
});
Is this not compatible with the Select component, because it works internally only with strings. So in this case the correct value is not selected:
<Select
label="Option"
{...form.getInputProps("option")}
/>
Now how can I solve this problem in an elegant way? Is there an API/option for this or do I really need to manually convert each numeric value into a string to make this compatible with Mantine?
Thanks a lot.
The code below should be self explanatory. If not, please read the #mantine/form package documentation.
import { Select } from "#mantine/core";
import { useForm } from "#mantine/form";
const data = [
{ value: "", label: "Select an option", disabled: true },
{ value: "1", label: "Option 1" },
{ value: "2", label: "Option 2" },
];
export default function MyForm() {
// create a form with initial values (field: value map)
// that match the `value`s defined in `data:
const form = useForm({
initialValues: {
status: "",
},
});
// create form submit handler:
const formOnSubmit = form.onSubmit(
(values) => console.log(values),
// optional, as form.getInputProps() can make inputs display the error themselves:
(errors) => console.error(errors)
);
return (
<form onSubmit={formOnSubmit}>
<Select
label="Status"
placeholder="Status"
data={data}
{...form.getInputProps("status")}
/>
<Group position="right" mt="md">
<Button type="submit">Submit</Button>
</Group>
</form>
);
}
I believe you can fix this by casting the type of the "value".
This is undocumented, and potentially could break with future releases, but you can do this:
import { Select } from "#mantine/core";
import { useForm } from "#mantine/form";
const data = [
{ value: '', label: 'Select' },
{ value: 2 as any, label: 'New' } // <-- here's the magic
];
export default function MyForm() {
const form = useForm({
initialValues: {
status: ''
},
});
return (
<form onSubmit={form.onSubmit((values) => console.log(values))}>
<Select label="Status" placeholder="Status"
data={data}
{...form.getInputProps('status')} />
<Group position="right" mt="md">
<Button type="submit">Submit</Button>
</Group>
</form>
);
}
I assume that what's happening inside the Select ultimately is some equality checks that will pass with numbers just as well as strings, so you get the correct item selected when it renders, and the correct value out when it submits.
I personally use this with a zodResolver that would complain bitterly about providing strings where it expects a number, and I'm loathe to make my zod schemas more complex to handle this problem.
To be fair, I can appreciate Mantine taking the approach of only supporting strings, since native HTML <select /> elements will always give you strings, and opening the door to anything else is probably a lot of work.
Still, seems like just providing the number value, and keeping typescript happy with as any (or you could do as unknown as string if you're not into the whole brevity thing) works a treat - at least for now!
I use this code:
import { Select } from "#mantine/core";
import { useForm } from "#mantine/form";
const data = [
{ value: '', label: 'Select' },
{ value: 2, label: 'New' }
];
export default function MyForm() {
const form = useForm({
initialValues: {
status: ''
},
});
return (
<form onSubmit={form.onSubmit((values) => console.log(values))}>
<Select label="Status" placeholder="Status"
data={data}
{...form.getInputProps('status')} />
<Group position="right" mt="md">
<Button type="submit">Submit</Button>
</Group>
</form>
);
}
I'm trying to update a State in my project based on a User Selection from a dropdown menu.
I passed the 2 states (roomType & occupants) along with their setter/change functions (onRoomTypeChange & onOccupantsChange) from the parent Component.
I’ve tried to read through the React Select Library, but having trouble.
Wondering if someone could point me in the right direction.
import React from 'react';
import Select from 'react-select';
const roomOptions = [
{ value: 'Standard', label: 'Standard' },
{ value: 'Delux', label: 'Delux' }
];
const occupantOptions = [
{ value: 1, label: '1' },
{ value: 2, label: '2' },
{ value: 3, label: '3' },
{ value: 4, label: '4' },
];
const RoomDetails = (props) => {
let {
roomType,
onRoomTypeChange,
occupants,
onOccupantsChange
} = props;
const handleChange = (e) => {
onRoomTypeChange(e.target.value);
};
return (
<div>
<div className="form-group">
<label className="select-label">Room Type: {roomType} </label>
<Select
// value={e.target.value}
onChange={handleChange}
options={roomOptions}
theme={theme}
/>
<label className="select-label">Guests: {occupants}</label>
<Select
value={occupants}
onDatachange={onOccupantsChange}
options={occupantOptions}
theme={theme}
/>
</div >
</div>
);
};
export default RoomDetails;
I resolved the and wanted to post an update:
I had installed another package called “react-dropdown-select” that I removed from my package.json, I believe was interfering with my react-select package .
The return object was not an event, it was the selected object from the corresponding options array. I destructured the value property in the parameter and used the Setter Function on the value only.
I originally included a Value= attribute on the Select Component, which was set to my current state value
<Select
value={stateProperty}
/>
When I removed the Value attribute, the bug was gone
(Here is the solution)
import React from 'react';
import Select from 'react-select';
const roomOptions = [
{ value: 'Standard', label: 'Standard' },
{ value: 'Delux', label: 'Delux' }
];
const occupantOptions = [
{ value: 1, label: '1' },
{ value: 2, label: '2' },
{ value: 3, label: '3' },
{ value: 4, label: '4' },
];
const RoomDetails = (props) => {
let {
onRoomTypeChange,
onOccupantsChange
} = props;
const handleChangeRoom = ({ value }) => {
console.log(value);
onRoomTypeChange(value);
};
const handleChangeOccupants = ({ value }) => {
console.log(value);
onOccupantsChange(value);
};
return (
<div>
<div className="form-group mb-2">
<span className="form-label mt-3">Room Type </span>
<Select
onChange={handleChangeRoom}
options={roomOptions}
theme={theme}
placeholder="Room Type"
/>
<span className="form-label mt-3">Guests</span>
<Select
onChange={handleChangeOccupants}
options={occupantOptions}
theme={theme}
placeholder="Number of Guests"
/>
</div >
</div>
);
};
export default RoomDetails;
I'm using react-select for choosing members for a project based on a team list.
The format of the options is as specified in the docs (array of objects with label and value)
const options = [
{label: "Sam Altman", value: "61b5b1a4f401d574f5cefab7"},
{label: "Sam B", value: "87tgb1a4f401d574f5cefab7"},
{label: "John Altman", value: "9o2nb1a4f401d574f5sd347"},
]
The problem arises when I'm trying to update the values in a different view. The selected values contains null option (where I auto populate the form with the created values)
My current select component is as follows: -
<Select
isMulti
options={options}
value={item}
onChange={(newMembers) =>
setValues({ ...values, assignedTo: newMembers || [] })
}
/>
The problem only arises while updating the created members
use values instead of value. below is sample code.
import { useState } from 'react';
import Select from 'react-select';
const options = [
{ label: "Sam Altman", value: "61b5b1a4f401d574f5cefab7" },
{ label: "Sam B", value: "87tgb1a4f401d574f5cefab7" },
{ label: "John Altman", value: "9o2nb1a4f401d574f5sd347" }
];
function App() {
const [values, setVaues] = useState([]);
return (
<div>
<Select
isMulti
values={values}
onChange={(newMembers) => setVaues({ ...values, assignedTo: newMembers || [] })} options={options}
/>
</div>
);
}
export default App;
I'm using Formik and React-select library and defaultValue is not working/taking effect and it remains empty, i don't know why this is happening.
MySelectInput component:
interface Props {
// .. other props
options: CategoryOptions[];
defaultCategory: CategoryOptions;
}
const MySelectInput: React.FC<Props> = (props) => {
const [field, meta, helpers] = useField(props.name);
return (
<>
<Select
options={props.options}
isSearchable
defaultValue={props.defaultCategory}
onChange={(v) => helpers.setValue(v!.value)}
onBlur={() => helpers.setTouched(true)}
placeholder={props.placeholder}
styles={customSelectStyles}
/>
</>
)
};
export default MySelectInput;
Usage:
<MySelectInput
options={CategoryOptions}
placeholder="Category"
name="category"
label="Category"
defaultCategory={{ value: activity.category, label: activity.category }}
/>
My array of objects (CategoryOptions):
export const CategoryOptions: CategoryOptions[] = [
{ value: 'drinks', label: 'Drinks' },
{ value: 'music', label: 'Music' },
{ value: 'travel', label: 'Travel' },
];
The options are working and displaying well but defaultValue is not working. If i use static strings inside object properties like:
defaultCategory={{ value: "test", label: "test" }}
is working well. Any idea?
I think you should probably use an item from CategoryOptions.
Instead of
defaultValue={props.defaultCategory}
do
defaultValue={props.defaultCategory[0]}
I'm also wondering why your CategoryOptions object is same as the CategoryOptions type. Maybe you should rename it to categoryOptions
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'all', label: 'all' },
{ value: 'destroyed', label: 'Destroyed' },
{ value: 'damaged', label: 'Damaged' },
{ value: 'physicalDamage', label: 'PhysicalDamage' }
]
class SearchFilters extends React.Component {
_onChange = (e, options) => {
const onChangeData = {
value: e.value,
name: e.label,
result: options.find(item => item.value === e.value)
};
console.log(onChangeData.value);
return onChangeData;
};
render(){
return(
<div>
<Select
options={options}
onChange={e => this._onChange(e, options)}
isMulti={true}
/>
</div>
)
}
}
export default SearchFilters
From the above code if isMulti is false in select, I'm able to print the value of the selected option in console, but if I change it to true, I get the value as undefined.
I need help in fixing this. Thanks in advance.
Ouput: