I am new to React and trying to figure out how to update state when a selection changes on an dropdown selection.
Here is my code:
page.js
import { useState } from 'react';
import SelectionRow from './selection-row';
export default function Home() {
const [positions, setPositions] = useState([
{id: 1, role : "Executive", selected_val: 2},
{id: 2, role : "Director", selected_val: 1},
{id: 3, role : "Manager", selected_val: 0},
{id: 4, role : "Staff", selected_val: 0}]);
function selectionChanged(e) {
}
return (
<main>
<form>
{positions.map((position) => (
<SelectionRow key={position.id} id={position.id} label={position.role} selected_val={position.selected_val} onSelectionChanged={selectionChanged}/>
))}
</form>
</main>
)
}
selection-row.js
const options = [
{ id: 0, name: "David"},
{ id: 1, name: "Andrew"},
{ id: 2, name: "Steven"},
{ id: 3, name: "Simon"},
];
export default function SelectionRow({id, label, selected_val, onSelectionChanged}) {
return (
<div>
<label>{label}</label>
<select onChange={onSelectionChanged} value={selected_val} id={id} name={id}>
{options.map((value) => (
<option value={value.id} key={value.id}>
{value.name}
</option> ))}
</select>
</div>
);
}
The sample application has an array of "company positions" that I want to populate with names chosen for a dropdown box for each. When the name is the dropdown box is changed, I want the selected_val in the positions array to be updated with id of the person selected.
Beyond passing a callback to the component, i’m unsure what I need to add in the selectionChanged function to update the positions array.
2
Answers
You can pass the
setPositions
function itself toSelectionRow
.Then on the
select
change handler, use theprevious
value from the state tofindIndex
the changes index of the original array, then update theselected_val
.Demo:
If you need more control in the Home component, or want to re-use this logic in another component, you could also define a updateX function:
Then pass that to the
SelectionRow
with an argument for the newselected_val
.Then you just need to call that function in the row:
Demo: