Skip to content

Instantly share code, notes, and snippets.

@rethna2
Created November 8, 2017 10:02
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 rethna2/18fed39c37447579a6b6b9ef8b98ccfa to your computer and use it in GitHub Desktop.
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.
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