user504909
user504909

Reputation: 9549

How to get TextField(Material-UI) value from hook react component?

I using Material-UI with react, have component like:

const UserDetail = (props: ListDetailProps) => {
    const oldpassword = useRef<TextFieldProps>(null);
    const newpassword = useRef<TextFieldProps>(null);
    const againpassword = useRef<TextFieldProps>(null);
    const handlePasswordChange = async () => {
        console.log(newpassword.current?.value)    //expect the password value but undefined get
        console.log(againpassword.current?.value)  //expect the password value but undefined get
    }
    return (<>
        <p>old password: <TextField ref={oldpassword} label="old password" type="password" /></p>
        <p>new password: <TextField ref={newpassword} label="new password" type="password" /></p>
        <p>new password: <TextField ref={againpassword} label="new password again" type="password" /></p>
        <button onClick={handlePasswordChange}>submit</button>
    </>
    )
}

I want get the value of ref TextField but get undefined. How to get the value of ref TextField?

I have read the answer of : React: How to get values from Material-UI TextField components,

But this answer for Form button, if I do not have form how to do it?

Upvotes: 3

Views: 6312

Answers (1)

Ido
Ido

Reputation: 5748

You need to use inputRef instead of ref.
That is because inputRef will pass a ref to the input element.

const UserDetail = (props: ListDetailProps) => {
    const oldpassword = useRef<TextFieldProps>(null);
    const newpassword = useRef<TextFieldProps>(null);
    const againpassword = useRef<TextFieldProps>(null);
    const handlePasswordChange = async () => {
        console.log(newpassword.current?.value)    //expect the password value but undefined get
        console.log(againpassword.current?.value)  //expect the password value but undefined get
    }
    return (<>
        <p>old password: <TextField inputRef={oldpassword} label="old password" type="password" /></p>
        <p>new password: <TextField inputRef={newpassword} label="new password" type="password" /></p>
        <p>new password: <TextField inputRef={againpassword} label="new password again" type="password" /></p>
        <button onClick={handlePasswordChange}>submit</button>
    </>
    )
}

You can refer to material-ui TextField API docs

Upvotes: 7

Related Questions