Abhishek Abhishek - 1 year ago 83
Javascript Question

How to access the html component from a composite component in react?

Consider this component

var React = require("react");

var Input = React.createClass({
return (<input {...this.props}/>)

module.exports = Input;

This is another component which uses the first component

var React = require('react');
var Button = require('./Button.react');
var Input = require('./Input.react');

var Form = React.createClass({
return( <div>
<Input ref = {(input) => this._user=input} placeholder='Username'/>
<Input ref = {(input) => this._pass=input} type="password" placeholder='Password'/>
<Button onClick={this.onPress}>Login</Button>
</div> )

module.exports = Form;

I want to access the value property of the of the first component. I understand that only the component constructor is available in the callback function provided for ref attribute.

So is there any way I can access the html component within the second component ?

I apologise if this question is duplicate , I am new to react and unfamiliar with the terminology.

leo leo
Answer Source

You can use refs

<Input ref = {(input) => this._pass=input} type="password" placeholder='Password'/>

and then


However, I suspect this is not what you want to do. You're trying to get the value from <Input />, but that should be done with onChange callback from <Input /> that's setting the value in its parent.

Something like...

var Input = React.createClass({
   render() {
    return <input {...this.props} onChange={this.props.handleChange} />

and in your parent you need to define handleChange callback, for example

handleChange(e) { 
  this.setState({ inputValue: e.target.value })
  // or possibly this.inputValue = inputValue

and pass it to the <Input />

<Input handleChange={handleChange} ... />

Then the <Input /> value will always be accessible: this.state.inputValue

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download