Phil Mok
Phil Mok

Reputation: 4050

Set React ref after component updates

I need to focus the user on a <Message /> component after they answer a question or change their answer. This message does not display on the initial render when the answer has not yet been answered.

When I try to focus() on the <Message /> component using a ref, I get the error message:

Cannot read property 'focus' of null

I think because this message renders only after the component updates. How can I set this ref after the component updates?

class MyComponent extends Component {

  componentDidUpdate(prevProps) {
    if (prevProps.answer !== this.props.answer) {
      console.log(this.message); // logs null
      this.message.focus(); // Cannot read property 'focus' of null
    }
  }

  render() {
    return (
      <div>
        { // if the user has answer the question, show a message
          this.props.answer !== null ?
            <Message
              ref={(message) => { this.message = message; }}
            /> 
            : null
        }
      </div> 
    );
  }
}

Edit

I just realized that because this Message component comes from semantic-ui, it might be a stateless functional component which would mean it cannot have a ref.

Upvotes: 1

Views: 2446

Answers (1)

Chase DeAnda
Chase DeAnda

Reputation: 16441

You can try to set the ref on a wrapper element instead of on the actual component:

class MyComponent extends Component {

  componentDidUpdate(prevProps) {
    if (prevProps.answer !== this.props.answer) {
      console.log(this.message); // logs null
      this.message.focus(); // Cannot read property 'focus' of null
    }
  }

  render() {
    return (
      <div>
        { // if the user has answer the question, show a message
          this.props.answer !== null &&
            <div ref={ message => this.message = message }>
              <Message/> 
            </div>
        }
      </div> 
    );
  }
}

Upvotes: 1

Related Questions