I have my select:
<Select
options={[
{ value: "1", label: "1" },
{ value: "2", label: "2" },
{ value: "3", label: "3" },
{ value: "4", label: "4" },
{ value: "5", label: "5" },
{ value: "6", label: "6" },
]}
name="mySelect"
ref={mySelect}
instanceId="mySelect"
defaultValue=""
onChange={() => getSelect(mySelect)}
/>
I have my function:
function getSelect(val) {
console.log(val.current.props.value["value"])
}
This logs the previous value, I understand why this happens but I can't think of another way to attempt this. Is there something similar to afterChange?
CodePudding user response:
To get the current value, you should be using the value from the onChange instead. You don't need ref for this
<Select
options={[
{ value: "1", label: "1" },
{ value: "2", label: "2" },
{ value: "3", label: "3" },
{ value: "4", label: "4" },
{ value: "5", label: "5" },
{ value: "6", label: "6" },
]}
name="mySelect"
ref={mySelect}
instanceId="mySelect"
defaultValue=""
onChange={(value) => getSelect(value)}
/>
function getSelect(val) {
console.log(val)
}
CodePudding user response:
It':
val.current.value
Not:
val.current.props.value
And since you are using ref so you don't need to send it throw parameter to handleChange function:
const mySelect = React.useRef(null);
function handleChange() {
if (mySelect.current) {
console.log(mySelect.current.value);
}
}
......
<Select
options={[
{ value: "1", label: "1" },
{ value: "2", label: "2" },
{ value: "3", label: "3" },
{ value: "4", label: "4" },
{ value: "5", label: "5" },
{ value: "6", label: "6" },
]}
name="mySelect"
ref={mySelect}
instanceId="mySelect"
defaultValue=""
onChange={handleChange}
/>