Body
Body

Reputation: 3688

Accessing input value from an element using ReactJs

How can I check wether an input field contains any value or not from another element. My attempt,

<div className='input-item'>
      <input ref="accessKey" name="username" className="lci-text" type="text"/>

      <label className={"helpers" + ((this.ref.accessKey.value.length > 0) ? 'toggled' : '')}>Access Key</label>
</div>

I'm trying to add a class '.toggled' to the label when the input has any values but getting the following error in console.

Uncaught TypeError: Cannot read property 'accessKey' of undefined

Update

I've also tried this.refs.accessKey.value.length this time getting the following error

Uncaught TypeError: Cannot read property 'value' of undefined

Please help me sort this.

Upvotes: 0

Views: 182

Answers (2)

Pierre
Pierre

Reputation: 19071

It's not recommended to access a ref directly to make changes in the same component. Additionally, since you are using react, you need make use of this.state.

As a side note, you should make use of the npm package classNames

Below is your updated code, using React State.

HTML

<div id="container"></div>

CSS

.helpers{ color: red }
.helpers.toggled{ color: green }

Javascript

var Hello = React.createClass({

  getInitialState: function() {
    return {value: ''};
  },

  handleChange: function(event) {
    this.setState({value: event.target.value});
  },

  render: function() {
    var toggled = this.state.value.length ? ' toggled' : '';

    return (
      <div>
        <input type='text'
          value={ this.state.value }
          onChange={ this.handleChange }
        />
        <label className={ 'helpers' + toggled }>Access Key</label>
      </div>
    );
  }

});

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

Fiddle

https://jsfiddle.net/qejxjo1x/2/


Official Notes and References:

  • Never access refs inside of any component's render method – or while any component's render method is even running anywhere in the call stack.

  • If you want to preserve Google Closure Compiler advanced-mode crushing resilience, make sure to never access as a property what was specified as a string. This means you must access using this.refs['myRefString'] if your ref was defined as ref="myRefString".

  • If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use refs to "make things happen" – instead, the data flow will usually accomplish your goal.

Upvotes: 2

shivam
shivam

Reputation: 16506

use refs instead of ref:

this.refs.accessKey.value.length

Upvotes: 0

Related Questions