0

I have got a react typescript project and have problems with login form.
Here's react login form code.

login-form.tsx

import * as React from 'react';
import {
    Button,
    FormGroup,
    Input,
    Label
} from 'reactstrap';
import {observer} from 'mobx-react';

@observer
export class LoginForm extends React.Component {
    form: any;
    username: any;
    password: any;
    OnLogin (){
      console.log("username:",this.username);
      console.log("username value:",this.username.value);
    }
    render(){
        return (
            <form className="form" ref={(form:any)=>{this.form = form}}>
                <FormGroup>
                    <Label>Sign In</Label>
                    <Input type="text" name="username" ref={(username:any)=>{this.username = username}} id="username" placeholder="enter your username"/>
                    <Input type="password" name="password" ref={(password:any)=>{this.password = password}} id="password" placeholder="enter your password"/>
                    <Button color="primary" onClick={this.OnLogin.bind(this)}>{"Login"}</Button>{' '}
                </FormGroup>
            </form>
        )
    }
}

Here, when I type my username artgb and click on Login button, OnLogin function print this line

username: Object { props: Object, context: Object, refs: Object, updater: Object, _reactInternalFiber: Object, _reactInternalInstance: Object, state: null }

username value:undefined

Error Image

I thought that username value should be artgb not undefined.

In fact I have just started typescript and can miss something basic.
Any kind of suggestion will be appreciate.

1

2 Answers 2

1

The value returned by the ref is a react component. So not a DOM element, for which you need to use ReactDOM.findDOMNode(this.username). This will return the DOM element, on which you can access the value property.

But as stated by Joe Clay, you do not need the refs. Use the event as described in the links he provided.

Sign up to request clarification or add additional context in comments.

4 Comments

According to the Reactstrap docs, in this case you can also access the innerRef prop on the React component to get the DOM element - might be a little more efficient, potentially.
Even better ! Not familiar with reactstrap, so I would not have know. :)
I got ReactDOM.findDOMNode(username) as input and console.log(ReactDOM.findDOMNode(username).nodeValue ) shows null
Replace nodeValue by value as you did before. Why do you use nodeValue?
0

I found easy solution.

OnLogin (){
  let formData: any = new FormData(form);
  console.log(formData.fd.get('upload_for'));
  console.log("username:",formData.fd.get('username'));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.