Brent Arias Brent Arias - 5 months ago 19
Javascript Question

Capturing React Refs via Event

I have the following JSX:

import React, {Component} from 'react';

class Register extends Component {
handleSubmit(){
console.log("hey!")
}

setHandles(c){
//This never executes.
console.log("foo");
}

render() {
return (
<form className='form-horizontal' onSubmit={this.handleSubmit}>
<h4>Create a new account.</h4>
<hr />
<div className="form-group">
<label htmlFor="Email" className="col-md-2 control-label">User Name</label>
<div className="col-md-10">
//********************************
//**** USING SETHANDLES HERE *****
//********************************
<input type="email" className="form-control" ref="{this.setHandles}" />
<span className="text-danger"></span>
</div>
</div>
<div className="form-group">
<label htmlFor="Password" className="col-md-2 control-label">Password</label>
<div className="col-md-10">
//********************************
//**** USING SETHANDLES HERE *****
//********************************
<input type="password" className="form-control" ref="{this.setHandles}" />
<span className="text-danger"></span>
</div>
</div>
...


My
setHandles
function never executes. Why?

My intent is to given each
input
the attribute
ref="{this.setHandles}"
so that the
setHandles
callback can register each corresponding DOM element. Later, when I am ready to post the form, I can loop through the array of DOM elements to grab the corresponding input values.

QoP QoP
Answer

It's not calling your function because you are passing a String, remove the quote marks, ref={this.setHandles}.

However, a better way to achieve what you want would be to assign an onChange event to every input in order to store the values in your state.

Something like this

constructor(props){
   this.onChange = this.onChange.bind(this);
   this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(){
   console.log(this.state); // You got your input values here
}
onChange(e){
    this.setState({[e.target.name] : e.target.value});
}
render(){
   return <div><form> 
    <input type="text" name="mail" className="form-control"
    onChange={this.onChange} />
    <input type="text" name="password"
    className="form-control" ref={this.setHandles} onChange={this.onChange} />
    <button onClick={this.onSubmit}>Submit</button>
   </form></div>
}

full working example

Comments