Let's say I have a <SelectPicker/>
component where I can select an option. What I want is how to add another <SelectPicker/>
after I selected an option.
function DynamicComponent() {
const [state, setState] = useState([
{ name: null, id: '1' },
]);
const handleAdd = (value) => {
// Updating logic
};
return(
<>
{ state.map(item => {
return <SelectPicker
onSelect={handleAdd}
key={item.id}
value={item.name}
data={options} />
})
}
</>
);
}
In the example above, let's say there is default SelectPicker which is not selected. After selection, I think handleAdd function should update object that has id equal to '1'
and add another object like this { name: null, id: '2' }
.
What is the best way to achieve such functionality in react? Any help would be appreciated. Thank you.
CodePudding user response:
On an abstract level, what you want to do is have an array of components inside your state which is then called by the Render function of DynamicComponent. This array should get its first SelectPicker component immediately, and every time handleAdd is called you add a new SelectPicker to the array using your setState function. You can get the id for each new SelectPicker component by finding array.length.
CodePudding user response:
In addition to the question, the below note from OP is also addressed in the below question
what if I want to update object's name property that has id:1 and add new object to state at the same time?
This may be one possible solution to achieve the desired result:
function DynamicComponent() {
const [myState, setMyState] = useState([
{name: null, id: '1'}
]);
const handleAdd = arrIdx => setMyState(prev => {
const newArr = [...prev];
prev[arrIdx]?.name = ">>>>----new name goes here---<<<<";
return [
...newArr,
{
name: null,
id: (prev.length 1).toString()
}
]
});
return(
<div>
{myState.map((item, idx) => (
<SelectPicker
onSelect={() => handleAdd(idx)}
key={item.id}
value={item.name}
data={options}
/>
)}
</div>
);
}
NOTES
- Avoid using variable-names such as "state"
- Passed the "index" from the
.map()
iteration - This helps in tracking the exact array-element
- The new element with
name: null
is added as the last - The
id
is calculated by incrementing the current length by 1