Created
November 8, 2017 10:02
-
-
Save rethna2/18fed39c37447579a6b6b9ef8b98ccfa to your computer and use it in GitHub Desktop.
This gist shows how to use 'ref' in React. It also shows how to have 'ref' in a child component which can be assessed from the parent component.
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'; | |
const Child = props => ( | |
<div | |
style={{ | |
width: 300, | |
height: 100, | |
backgroundColor: '#bbb', | |
border: '1px solid gray', | |
}} | |
> | |
<h4> Nested Inner Component </h4> | |
<div> | |
<label> Inner Text Input: </label> | |
<input type = "text" ref={props.childComponentRef} /> | |
</div> | |
</div> | |
); | |
class Index extends React.Component { | |
constructor() { | |
super(); | |
this.childComponentRef = null; | |
this.sameComponentRef = null; | |
} | |
getValueFromRef = () => { | |
this.forceUpdate(); | |
} | |
render() { | |
return ( | |
<div style={{ margin: 50 }}> | |
<h1> Refs </h1> | |
<h4> Outer Text Input : { this.sameComponentRef ? this.sameComponentRef.value : 'none' } </h4> | |
<h4> Inner Text Input : { this.childComponentRef ? this.childComponentRef.value : 'none' } </h4> | |
<div> | |
<label> Outer Text Input: </label> | |
<input type= "text" ref={ n => this.sameComponentRef = n } /> | |
</div> | |
<Child childComponentRef={ n => this.childComponentRef = n} /> | |
<button onClick = {this.getValueFromRef} > Get Value From Ref </button> | |
</div> | |
); | |
} | |
} | |
export default Index; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment