Reputation: 2159
I am trying to access my email and password field through ref
but I get an undefined value no matter what.
Here is my code:
import React, { Component } from 'react'
import { Button,
Modal,
ModalHeader,
ModalBody,
ModalFooter,
Form,
FormGroup,
Input
} from 'reactstrap';
class LoginModal extends Component {
constructor(props) {
super(props);
this.email = React.createRef();
this.password = React.createRef();
};
login (e) {
e.preventDefault();
const email = this.email
const password = this.password
console.log(email, password)
}
render () {
return (
<Modal>
<ModalHeader>Connexion</ModalHeader>
<ModalBody>
<Form onSubmit={this.login}>
<FormGroup>
<Input type="email" name="email" ref={this.email} placeholder="Email" />
</FormGroup>
<FormGroup>
<Input type="password" name="password" ref={this.password} placeholder="Mot de passe" />
</FormGroup>
<Button type="submit" color="primary">CONNEXION</Button>
</Form>
</ModalBody>
<ModalFooter>
Footer
</ModalFooter>
</Modal>
)
}
}
export default LoginModal
I am using react 16.5.2.
I did this according to the doc: here
Upvotes: 2
Views: 3207
Reputation: 85545
You need to bind the method inside your constructor:
this.login = this.login.bind(this)
And also to get ref value, you will use current
login (e) {
e.preventDefault();
const email = this.email
const password = this.password
console.log(email.current.value, password.current.value)
}
Upvotes: 1