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
};
ponentDidMount() {
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 ponent, that error suddenly occurs. And it says TypeError: Cannot read property 'focus' of undefined
The error is occured at ponentDidMount
Can you take the time to help me fix this error?
I can't understand why this error is ing up
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
};
ponentDidMount() {
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 ponent, that error suddenly occurs. And it says TypeError: Cannot read property 'focus' of undefined
The error is occured at ponentDidMount
Can you take the time to help me fix this error?
I can't understand why this error is ing up
Share Improve this question asked Dec 25, 2019 at 15:06 Dann1yDann1y 5071 gold badge5 silver badges9 bronze badges 02 Answers
Reset to default 4From what I can see, title
is not a class property of your InputSet
ponent.
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,
ponentDidMount() {
if (this.title.current) {
this.title.current.focus();
}
}
You have to add .current
like this this.title.current.focus();
Hope this helps