Auto selected of value from options in react-select react - reactjs

Problem Statement :
I am using react-select 2.4.1 for the Select dropdown.
I want to auto select the value from options array based on some condition, and that auto selected value should also get updated in the component state or vice versa.
How can I achieve that?
I have tried multiple ways, please help.
Thanks in advance.
Below is my code for the Select dropdown.
<Select
options={props.mercModeOptions}
onChange={(evt) => setSelectedMercMode(evt.value)}
selected={props.mercModeDefaultOpt}
/>
Below is the options array:
props.mercModeOptions = [
{
value: "first",
label: "first"
},
{
value: "second",
label: "second"
},
{
value: "third",
label: "third"
}
]
Value to be auto selected:
props.mercModeDefaultOpt = {
value: "third",
label: "third"
};

I have added sample codesandBox to achieve this.
We can store the default value in a variable using the useMemo hook and update the local state.
import Select from "react-select";
import { useEffect, useMemo, useState } from "react";
const dropDowonData = [
{ value: "first", label: "first" },
{ value: "second", label: "second" },
{ value: "third", label: "third" }
];
export default function App() {
const [selectedValue, setSelectedValue] = useState();
// This will run for only during the first render.
const defaultSelectedValue = useMemo(() => {
// to update the local state
setSelectedValue(dropDowonData[0]);
return dropDowonData[0];
}, []);
console.log(selectedValue);
return (
<div className="App">
<Select
defaultValue={defaultSelectedValue}
value={selectedValue}
onChange={(value) => setSelectedValue(value)}
name="Select"
options={dropDowonData}
/>
</div>
);
}

Related

React-select fills an null value option when I try to update a created object

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;

How to passe value from dropdown made by semantic ui in react

I have problem with this select by semantic ui. I made object with values I mapping it, state is changing but value in Select is not updating - if I put props as default value, it is like hard coded, and not changing at all. So what i can do (e target value doesnt work) to pass the selected icon to change props state? Should i use hook?
import React from 'react';
import { Dropdown } from 'semantic-ui-react';
const Dropdown = () => {
let icons = [
{
"v1": "home",
"ico": "home"
},
{
"v1": "cart",
"ico": "cart"
},
{
"v1": "folder",
"ico": "folder"
},
{
"v1": "group",
"ico": "group"
},
{
"v1": "dollar",
"ico": "dollar"
},
{
"v1": "users",
"ico": "users"
},
{
"v1": "briefcase",
"ico": "briefcase"
},
{
"v1": "globe",
"ico": "globe"
},
{
"v1": "calendar",
"ico": "calendar"
},
{
"v1": "favorite",
"ico": "favorite"
},
];
const options = icons.map(({ v1, ico }) => ({ value: v1, icon: ico }))
return(
<div>
<Dropdown
text='Add icon'
icon='add circle'
floating
labeled
button
className='icon'
value={prop.icon}
options={options}
name='icon'
></Dropdown>
</div>
)
}
You can pass an onChange function to the component that receives two arguments: event and result. The result argument is an object that has a key value with the selected value of the dropdown. You then need to use the useState hook to save the selected value in the component state.
Hence, you could do something like this:
import {useState} from "react"
const [value, setValue] = useState("")
const handleChange = (e, result) => {
// result.value is the selected value from the Dropdown
setValue(result.value)
}
<Dropdown
onChange={handleChange}
/>

React combo doesnt select proper value

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.

How to display multiple selected values from a dropdown in React

I'm new to React and I wanted to create a dropdown which can select multiple values. For that I used the react-select plugin. In my React dev tool the selected values are getting stored but I'm not able to display all the selected values.
Any help is highly appreciated.
TIA
import React, { useState } from "react";
import Select from 'react-select'
const options = [
{ value: 'React', label: 'React' },
{ value: 'Vue', label: 'Vue' },
{ value: 'Angular', label: 'Angular' },
{ value: 'Java', label: 'Java' },
]
const [skills, setSkills] = useState([]);
const handleChange = (skill) => {
setSkills({skill})
console.log("skills", skill);
}
return (
<>
<h2>Please select all your skills</h2>
<form>
<Select
options={options}
onChange={handleChange}
isMulti={true}
value={value}
/>
<button>Next</button>
</form>
</>
)
}
export default UserSkills;
When I'm commenting isMulti prop, I'm getting that one selected value, but I'm not getting anything with isMulti prop.
You are controlling the Select component by giving it a value, and since you are not updating value in the handleChange function it will not be updated.
You could use the skills array as value instead and it will update as expected.
CodeSandbox
const options = [
{ value: "React", label: "React" },
{ value: "Vue", label: "Vue" },
{ value: "Angular", label: "Angular" },
{ value: "Java", label: "Java" }
];
function UserSkills() {
const [skills, setSkills] = useState([]);
const handleChange = (skills) => {
setSkills(skills || []);
};
return (
<>
<h2>Please select all your skills</h2>
<form>
<Select
options={options}
onChange={handleChange}
value={skills}
isMulti
/>
<button>Next</button>
</form>
</>
);
}
export default UserSkills;

How to retrieve selectedRows from a material-table in React

I have a material table and I use selection and filtering.
Above my material table I have a button that should "send" the selected rows to its parent if you click on it.
How can I retrieve the selected Rows though? I know I can do
const [selectedRows, setSelectedRows] = useState([]);
<MaterialTable
...
onSelectionChange={(rows) => {
setSelectedRows(rows);
}}
... />
But the setSelectedRows results in the Table to be rerendered and then all my filters are gone. I know I could store filters in a state too , but this sounds like way too much overhead for just the simpe question to retrieve the selectedRows at a certain point in time.
Any easy suggestions?
Thanks a lot for your help
Use the components prop and lift the FilterRow component into parent state like below. The filter values will persist.
import MaterialTable, { MTableFilterRow } from 'material-table';
const Parent = () => {
const [components, whatever] = useState({
FilterRow: props => <MTableFilterRow {...props} />,
});
const [columns] = useState([
{ title: "Name", field: "name" },
{ title: "Pet", field: "pet" }
]);
const [data] = useState([
{ name: "Jim", pet: "Dog" },
{ name: "Tom", pet: "Horse" },
{ name: "Susan", pet: "Rat" },
{ name: "Penny", pet: "Cat" }
]);
return (
<MaterialTable
columns={columns}
data={data}
components={components}
/>
);
}
``
Add a ref to the component
<MaterialTable
tableRef={tableRef}
you can get selected rows with
tableRef.current.dataManager.data.filter(o => o.tableData.checked)

Resources