Skip to content

Instantly share code, notes, and snippets.

@nilshartmann
Created February 28, 2017 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilshartmann/81328b1e4089e873dde55fca950a629c to your computer and use it in GitHub Desktop.
Save nilshartmann/81328b1e4089e873dde55fca950a629c to your computer and use it in GitHub Desktop.
Access React Component using 'ref'
import React from 'react';
import ReactDOM from 'react-dom';
class Input extends React.Component {
constructor() {
super();
this.state = {
greeting: ''
}
}
render() {
return <input
onChange={event => this.setState({greeting: event.target.value})}
value={this.state.greeting}/>
}
getCurrentValue() {
return this.state.greeting;
}
}
class HelloMessage extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<div>
<Input ref={r => this.inputField = r}/>
<button
onClick={() => this.getValueFromInputField()}>
Get value from input
</button>
{this.state.valueFromInput && <p>Value from input: {this.state.valueFromInput}</p>}
</div>);
}
getValueFromInputField() {
this.setState({valueFromInput: this.inputField.getCurrentValue()});
}
}
const mountNode = document.getElementById('mount');
ReactDOM.render(<HelloMessage greeting="Hello"/>, mountNode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment