Tell me please, how can I set defaultValue in Multiple Search Selection Dropdown? I tried to set array of object like discribe in docs, but I do not receive what I want
constructor(props) {
super(props);
this.state = {
specs: [],
doctorSpecs: []
}
this.profileService = new ProfileService();
this.addSpecializationsService = new SpecializatoinsService();
}
componentWillMount() {
this.profileService.getProfileInformation()
.then((res) => {
this.setState({
profile: res.data,
consultationFees: res.data.consultation_fees,
mpdbRegistrationNumber: res.data.mpdb_registration_number,
qualification: res.data.qualification,
experienceYears: res.data.experience_years,
doctorSpecs: res.data.specializations.map((elem, index) => {
return {key: index, value: elem.id, text: elem.name}
})
})
})
this.addSpecializationsService.getSpecializationsList("", (res) => {
console.log(res);
this.setState({
specs: res.data.body.map((elem, index) => {
return {key: elem.id, value: elem.id, text: elem.name}
})
})
});
}
// other nessesary code
// component where must be this.state.doctorSpecs
<Dropdown
className='profile-specs'
placeholder='Skills'
fluid multiple selection search
options={this.state.specs}
onChange={this._onChangeSpecs}
value={this.state.doctorSpecs}
onSearchChange={this._getListSpecs}/>
I want , after render component, display array of values in this dropdown
I tried to use value, defaultValue, but it's not work
I find a problem.
I had to transfer to the array not objects, but text values from this objects
Related
I am trying to implement a MultipleSelectList from this library react-native-dropdown-select-list. And I am saving the selected items in the AsyncStorage of #react-native-async-storage/async-storage. I implemented 2 useState variables: first const [selected, setSelected] = useState([{}]); this is a list of {name : muscleGroup, value : id(s) of the exercise(s)} (this is the object that is saved in the list of viewDataList [see setExerciseViewLists ]). The other useState variable that I have implemented is:
const [selectedCount, setSelectedCount] = useState({ // a list of the number of selected exercises per muscleGroup
Back: 0,
Legs: 0,
Chest: 0,
.....
});
The idea: when I call handleSelect (see handleSelect) from my MultipleSelectList I give it 2 parameters (val and item) val should be the id(s) of the exercise(s) because I defined it as this in my MultipleSelectList (see MultipleSelectList) and the item is one list item from viewDataList.
The problem is: val is for some reason, not an ID or a list of IDs, it is an anonymous function:
function (val) {
var temp = _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(new
Set([].concat(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(val),
[value])));
return temp;
}
(I don't really understand what this is). Any help would be appriciated.
MultipleSelectList
{viewDataList.map((item, index) => (
<MultipleSelectList
data={item.list.map(listItem => ({
value: listItem.id, //here
}))}
save="value"
setSelected={(val) => handleSelect(val, item)}
selected={selected.map(item => item.value)}
/>
))}
handleSelect/Async saving
const handleSelect = async (val, item) => {
setSelectedCount(prevState => ({
...prevState,
[item.name]: prevState[item.name] + 1, //item.name = muscleGroup
}));
setSelected(prevState => ([
...prevState,
{
name: item.name,
value: val //val should be the ID(s)
},
]));
try {
await AsyncStorage.setItem('selected', JSON.stringify([
...selected,
{
name: item.name,
value: val,
}
]));
await AsyncStorage.setItem('selectedCount', JSON.stringify({
...selectedCount,
[item.name]: selectedCount[item.name] + 1,
}));
} catch (e) {
console.e('Error saving data to AsyncStorage:', e);
}
};
setExerciseViewLists
const setExerciseViewLists = () => {
let list = [];
list.push(
{.....},
{
num: 3,
name: "muscleGroup",
list: [{.....}, { id: "123", exercises : "somthing" }, {.....}]
},
{.....},
);
setViewDataList(list);
};
The issue is not with your data but with the setSelected prop for which you are sending a custom function handleSelect. But if you see the library's documentation, it is clearly mentioned like setSelected is for For Setting the option value which will be stored in your local state. So you can only store the selected values in the local state. The code should be like below inside the component.
const [selectedValues, setSelectedValues] = useState();
return <MultipleSelectList
data={SOME_DATA}
save="value"
setSelected={setSelectedValues}
/>
I have this state
this.state = {
dropdown1: false,
dropdown2: false,
dropdown3: false
}
I want to access to these dropdowns in state using this.setState but the number after 'dropdown' comes from API
onMaca = (ev) => {
this.setState({
dropdown + ev: true
})
}
So I want the key to be dynamic 'dropdown1' for example.
Thanks for your answers
you can access the object property like this object['property name']
onMaca = (ev) => {
this.state['dropdown' + ev]= true;
this.setState({
...this.state
})
}
https://codezup.com/add-dynamic-key-to-object-property-in-javascript/
You can use any of these to set key dynamically. I will try to update the answer with an example in a while for setState.
The state is a JS object, so you can get its keys as usual, like so:
const stateKeys = this.state.keys()
Now you have an array: [ "dropdown1", "dropdown1", "dropdown1" ]
One way to use it would be:
const keysMap = statekeys.map(( item, i ) => return {
key: item,
idx: i,
number: item.replace( /dropdown/, '' )
}
keysMap will look like so: [ { key: 'dropdown1', idx: 0, number "1" }, { key: 'dropdown1', idx: 1, number "2" }, { key: 'dropdown1', idx: 2, number "3" } ]
You can query keysMap for a given dropDownNumber like so:
let k = keysMap.find( kmap => kmap.key = dropDownNumber )
To set the dropdown's state:
this.setState({ k: <whatever> })
I've been trying to search for this in the docs but couldn't find anything
I'm trying to update my array 'myGamesArray' with the string 'query' and 'image'.
This is a multi-dimensional array and I want to update the first column with 'query' and the second column with 'image'.
I tried this here but it did not work:
constructor(props) {
super(props);
//Initialization of state
//films will contain the array of suggestion
//query will have the input from the autocomplete input
this.state = {
myGamesArray:[{name: "", img: ""}],
games: [],
query: ' ',
image: '',
};
}
this.setState(prevState => {
const { myGamesArray, query, image } = prevState;
return {
myGamesArray: [...myGamesArray[0][0], query.toString()],
myGamesArray: [...myGamesArray[0][1], image.toString()],
query:''
};
},
you should change the myGamesArray once then return it, also spread the prevState so the old values are preserved, so the could should look something like this:
this.setState(prevState => {
const { myGamesArray, query, image } = prevState;
myGamesArray.unshift({
name: query.toString(),
img: image.toString(),
});
return {
...prevState
newGameArray,
query:'',
};
},
I use Table component from Ant-design to search, filtering and sort a big set of data but I have a problem with "Select all Data".
For example if I click on checkbox on top of table, only display rows on screen are selected. So if I change of page, the others rows aren't selected. If I want select all data I need to custom selection and use rowSelection.selections.
As you can see on this example extract from ant.design website below,
the proposal solution is to write directly all keys of row that I need to select, but if I have filtered just before one column I can't know the state of my props datasource.
So my question is: How can I know all the data currently available on the screen?
For example, If there is 10 pages initially, and then I filter and sort, and now there is 2 pages, how get the array of new set of data.
Thanks in advance. 👍
class App extends React.Component {
state = {
selectedRowKeys: [], // Check here to configure the default column
};
onSelectChange = (selectedRowKeys) => {
console.log('selectedRowKeys changed: ', selectedRowKeys);
this.setState({ selectedRowKeys });
}
render() {
const { selectedRowKeys } = this.state;
const rowSelection = {
selectedRowKeys,
onChange: this.onSelectChange,
hideDefaultSelections: true,
selections: [{
key: 'all-data',
text: 'Select All Data',
onSelect: () => {
this.setState({
selectedRowKeys: [...Array(46).keys()], // 0...45
});
},
}, {
key: 'odd',
text: 'Select Odd Row',
onSelect: (changableRowKeys) => {
let newSelectedRowKeys = [];
newSelectedRowKeys = changableRowKeys.filter((key, index) => {
if (index % 2 !== 0) {
return false;
}
return true;
});
this.setState({ selectedRowKeys: newSelectedRowKeys });
},
}, {
key: 'even',
text: 'Select Even Row',
onSelect: (changableRowKeys) => {
let newSelectedRowKeys = [];
newSelectedRowKeys = changableRowKeys.filter((key, index) => {
if (index % 2 !== 0) {
return true;
}
return false;
});
this.setState({ selectedRowKeys: newSelectedRowKeys });
},
}],
onSelection: this.onSelection,
};
return (
<Table rowSelection={rowSelection} columns={columns} dataSource={data} />
);
}
}
You can try this props on Table
onChange: Callback executed when pagination, filters or sorter is changed
Function(pagination, filters, sorter, extra: { currentDataSource: [] })
The currentDataSource might be the thing you want.
I am trying to update the property of an object which is stored in an array.
my state looks something like this:
state = {
todos: [
{
id: '1',
title: 'first item,
completed: false
},
{
id: '2',
title: 'second item,
completed: false
}
],
}
What I am trying to do is access the second element in the 'todos' array and update the completed property to either false -> true or true -> false.
I have a button with the handler for update, and my class method for the update looks like this:
onUpdate = (id) => {
const { todos } = this.state;
let i = todos.findIndex(todo => todo.id === id);
let status = todos[i].completed
let updatedTodo = {
...todos[i],
completed: !status
}
this.setState({
todos: [
...todos.slice(0, i),
updatedTodo,
...todos.slice(i + 1)
]
});
}
While this does work, I want to find out if there is a more concise way of achieving the same result; I tried to use Object.assign(), but that didn't work out because my 'todos' is an array, not an object. Please enlighten me with better code!
It would be best to use update function to make sure you don't work on outdated data:
onUpdate = (id) => {
this.setState(prevState => {
const copy = [...prevState.todos];
const index = copy.findIndex(t => t.id === id);
copy[index].completed = !copy[index].completed;
return { todos: copy }
})
}
You can simply copy your todos from state, then make edits, and after that put it back to the state
onUpdate = (id) => {
var todos = [...this.state.todos]
var target = todos.find(todo => todo.id == id)
if (target) {
target.completed = !target.completed
this.setState({ todos })
}
}