Nik
Nik

Reputation: 31

React Ref: Uncaught TypeError: Cannot set property 'innerHTML' of null

I have these refs in my constructor

constructor(props) {
    super(props);

    //All Refs
    this.sunglassesTintsTab = React.createRef();
    this.gradientTintsTab = React.createRef();
    this.fashionTintsTab = React.createRef();
    this.lensTintStandardSwatchesContainer = React.createRef();
    this.lensTintMirrorSwatchesContainer = React.createRef();
}

And this is my componentDidMount

  componentDidMount() {
    console.log('ComponentDidMount Start');
    if (this.state.modalType === 'lensTintsBlokz') {
      this.getLensTintSwatches('blokz');
    } else {
      this.setState({ lensTintsTabsContainerHidden: false });
      this.getLensTintSwatches('sunglasses');
    }
  }

In the getLensTintSwatches function - this is being called in componentDidMount

this.lensTintStandardSwatchesContainer.current.innerHTML = '';
this.lensTintMirrorSwatchesContainer.current.innerHTML = '';

I'm getting the following error.

Uncaught TypeError: Cannot set property 'innerHTML' of null

I have tried both the standard React.createRef() and callback style ref but the current value of all the refs is returning null. What am I doing wrong here?

UPDATE: I'm passing ref={this.xyxRef} as prop in the respective elements.

Another observation- The console.log in componentDidMount is not triggered, based on other console errors

This is the flow:

Constructor -> Render -> Constructor -> Render -> This ERROR

Upvotes: 3

Views: 4095

Answers (1)

Eusbolh
Eusbolh

Reputation: 126

The most likely reason why you are getting the error is that your refs are not attached to a DOM element. If you are not trying to attach these refs to a DOM element, that means that you didn't set the initial values of your refs. Either way, the error says that your refs' values are null somehow. So, you can either:

  • Pass your refs into an html element (e.g. <div ref={myRef} />), then React will automatically set your ref's .current property to the corresponding DOM node.
  • Give an initial value to your refs. (As far as I know, you are not able to give an inital value to refs with createRef. You might need to convert your component into a functional component and then you can use useRef hook to give initial value to your refs.)

To have more info about refs, I suggest you to read the React's official documentation about refs.

Upvotes: 3

Related Questions