Sandrina Pereira Sandrina Pereira - 13 days ago 6
Javascript Question

React : get Form values from children component on submit

Resume: I have a

SignForm
component that is used multiple times by parent components and I can't figured out a way to pass the
input values
from
SignForm
to the parent Component.

I already searched for it, found some similar questions but on my case it doesn't work :/




Login : the parent component that calls the SignForm

class Login extends React.Component {

constructor() {
//... code
}

render() {
return (
<SignForm
cta='Go'
switchSign='Create account'
handleSubmit={this._handleSubmit}
/>
)
}

_handleSubmit(username, password) {
console.log(username, password);
this._validateUser(username, password);
}

_validateUser(username, password) {
//....
}
}


SignForm : the children component that contains the form markup

class SignForm extends React.Component {

constructor() {
super();
var self = this;
}

render() {
return (
<form className="Form" onSubmit={this._onSubmit.bind(this)}>
<div className="Form-body">
<p className="InputSide">
<input id="username" type="text" name="username" ref={(input) => this._username = input}/>
<label htmlFor="username">Username</label>
</p>

<p className="InputSide">
<input id="password" type="pass" name="password" ref={(input) => this._password = input}/>
<label htmlFor="password">Password</label>
</p>
</div>

<div className="Form-footer">
<button type="submit" name="sign" className="BtnBasic--lg">{this.props.cta}</button>
<Link to="/login" className="Link">{this.props.switchSign}</Link>
</div>
</form>

)
}

_onSubmit(e) {
e.preventDefault();
console.log(this._username.value, this._password.value); //it logs the input values.
self.props.handleSubmit(this._username.value, this._password.value); //error
}
}


The view renders without problems displaying the props passed to SignForm. The problem is on the form submit: The last line
self.props.handleSubmit(this._username.value, this._password.value);
return an error:


"Uncaught TypeError: Cannot read property 'handleSubmit' of undefined(…)"


Thanks.

Update: I found a solution, check my answer below

Answer

If you have functions inside your component other than the constructor and Component's lifecycle method (render, componentWillMount, componentDidMount, etc...), and you'll be using the this keyword to access class method or props or state, you'll need to bind the this. You can do so inside your constructor.

constructor(props) {
   super(props);
   this._handleSubmit = this._handleSubmit.bind(this);
}

That way, you don't have to bind it on every caller...

<form onSubmit={this._handleSubmit} />