Dann1y
Dann1y

Reputation: 497

TypeError: Cannot read property 'focus' of undefined in ReactJS

import React, { Component } from "react";
import PropTypes from "prop-types";
import Textarea from "react-textarea-autosize";

class InputSet extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }


  static propTypes = {
    onChange: PropTypes.func,
    title: PropTypes.string,
    body: PropTypes.string
  };

  componentDidMount() {
    this.title.focus();
  }

  render() {
    const { onChange, title, body } = this.props;

    return (
      <div>
        <TitleInput
          name="title"
          onChange={onChange}
          placeholder="Title"
          innerRef={ref => (this.title = ref)}
          value={title}
        />
        <StyledTextArea
          minRows={3}
          maxRows={20}
          placeholder="Please enter a note..."
          name="body"
          onChange={onChange}
          value={body}
        />
      </div>
    );
  }
}

export default InputSet;

When I click on a component, that error suddenly occurs. And it says TypeError: Cannot read property 'focus' of undefined

The error is occured at componentDidMount

Can you take the time to help me fix this error?

I can't understand why this error is coming up

Upvotes: 2

Views: 9880

Answers (2)

wentjun
wentjun

Reputation: 42596

From what I can see, title is not a class property of your InputSet component.

I believe you meant to make use of the React.createRef() API to attach the ref to your React element.

this.title = React.createRef();

On your constructor,

constructor(props) {
  super(props);
  this.state = {};
  this.title = React.createRef();
}

And then,

componentDidMount() {
  if (this.title.current) {
    this.title.current.focus();
  }
}

Upvotes: 4

Shmili Breuer
Shmili Breuer

Reputation: 4147

You have to add .current like this this.title.current.focus();

Hope this helps

Upvotes: 1

Related Questions