0

I just wanted to add a ref to object because I have to clear its value. I wrote like :

this.code = (
    <div className="form-group">
          <label className="form-label" htmlFor="target">Target</label>
          <input className="input" onChange={this.handleChange.bind(this)} ref="textbox" id="target" type="text" placeholder="Target" />
        </div>
);
this.setState(this.state);

And got an error like:

Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded

All I want to do is simple : If I click a button, the existing form will be cleared, and some other form will come up. To do that, I tried using a setState method. Is it a wrong approach?

Hoseong Son
  • 247
  • 4
  • 18

1 Answers1

0

Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded

According to the React Docs:

This usually means one of two things:

1. You are trying to add a ref to an element that is being created outside of a component's render() function.
2. You have multiple (conflicting) copies of React loaded (eg. due to a misconfigured NPM dependency)

You case seems to be the first one, where you are trying to create the document object outside of your render function.

The solution would be to have a function called from the render function that returns a document object

renderInput = () => {
    return (
        <div className="form-group">
          <label className="form-label" htmlFor="target">Target</label>
          <input className="input" onChange={this.handleChange.bind(this)} ref={(ref) => this.textbox = ref} id="target" type="text" placeholder="Target" />
        </div>
    )
}
render() {
   return (
       <div>
            {this.renderInputForm()}
      </div>
   )
}

P.S. React suggests to use callback approach for refs instead of string refs. Check this answer:

In React .js: is there any function similar like document.getElementById() in javascript ? how to select certain object?

Also in case of Invalid Refs:

Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's render method). Try rendering this component inside of a new top-level component which will hold the ref.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400