Reputation: 12516
I try to start this official React code example with my code:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
// my code
const e = new CustomTextInput();
const root = document.getElementById("root");
ReactDOM.render(e, root);
but I get the error:
Invariant Violation
Objects are not valid as a React child (found: object with keys {props, context, refs,
updater, textInput, focusTextInput}). If you meant to render a collection of children,
use an array instead.
Why does it happen?
Upvotes: 0
Views: 155
Reputation: 85593
You simply need to use:
ReactDOM.render(<CustomTextInput />, root);
And avoid using:
const e = new CustomTextInput(); // delete this
React accepts element not instance to render:
ReactDOM.render(element, container[, callback])
Upvotes: 1
Reputation: 11610
You're creating a component instance yourself here:
const e = new CustomTextInput();
You need to let React do it internally and instead pass it a React element:
const e = <CustomTextInput/>;
that looks like this:
{
"type": "CustomTextInput",
"key": null,
"ref": null,
"props": {},
"_owner": null
}
Upvotes: 2