Created
February 28, 2017 10:52
-
-
Save nilshartmann/81328b1e4089e873dde55fca950a629c to your computer and use it in GitHub Desktop.
Access React Component using 'ref'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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