Component's props names and local state variable names are collide. Is there any naming convention followed globally? See "selected" props and state
function Select({options,selected,onSelect}){
let [selected,setSelect]=useState(selected)
//... useeffect to update local state if props changes
function setSelectLocal(){
setSelect(e.target.value)
onSelect(e.target.value)
}
return (
<select onChange={onSelect} value={selected}>
{options.map((option)=><option>{option}</option>)}
</select>
)
}
Thanks
I would say const [selectedValue, setSelectedValue] = useState('default value')
.
However, what might be a better option is let the parent component handle the state and simply pass down the handler via props.
function ParentComponent() {
const [selectedValue, setSelectedValue] = useState('default value')
const onChange = (e) => {
setSelectedValue(e.target.value)
}
return (
<div>
// other stuff here
<ChildComponent options={stuff} onChange={onChange} selectedValue={selectedValue} />
</div>
)
}
function ChildComponent({ options, onChange, selectedValue }) {
return (
<select onChange={onChange} value={selectedValue}>
{options.map((option)=><option>{option}</option>)}
</select>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With