A am using react-rails gem in my ruby on rails project. I try to add reference to my DOM element. This is my ponent:
class NewItem extends React.Component {
constructor(props) {
super(props);
this.name = React.createRef();
}
handleClick() {
var name = this.name.value;
console.log(name);
}
render() {
return (
<div>
<input ref={this.name} placeholder='Enter the name of the item' />
<button onClick={this.handleClick}>Submit</button>
</div>
);
}
};
When i try to load the page in browser i have this message in console:
TypeError: React.createRef is not a function. (In 'React.createRef()', 'React.createRef' is undefined)
.
A am using react-rails gem in my ruby on rails project. I try to add reference to my DOM element. This is my ponent:
class NewItem extends React.Component {
constructor(props) {
super(props);
this.name = React.createRef();
}
handleClick() {
var name = this.name.value;
console.log(name);
}
render() {
return (
<div>
<input ref={this.name} placeholder='Enter the name of the item' />
<button onClick={this.handleClick}>Submit</button>
</div>
);
}
};
When i try to load the page in browser i have this message in console:
TypeError: React.createRef is not a function. (In 'React.createRef()', 'React.createRef' is undefined)
.
- are u using latest version of react? – Gautam Naik Commented May 1, 2018 at 19:14
- @GautamNaik yes – Herman Eyd Commented May 1, 2018 at 19:34
2 Answers
Reset to default 13update react to 16.3 React.createRef() this API is added on react 16.3 checkout this https://github./facebook/react/pull/12162
Try changing this
handleClick() {
var name = this.name.value;
console.log(name);
}
to
handleClick = () => {
var name = this.name.current.value;
console.log(name);
}
Dont use ref for getting value of input. Use this method
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}