Skip to content

Instantly share code, notes, and snippets.

@react-ram
Last active July 21, 2019 13:45
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 react-ram/a0164a14f9df0f053887e98f4348e132 to your computer and use it in GitHub Desktop.
Save react-ram/a0164a14f9df0f053887e98f4348e132 to your computer and use it in GitHub Desktop.
EXAMPLE FOR : forwarding Ref's
function App() {
return (
<div className="App">
<Parent />
</div>
);
}
//child
const Child = React.forwardRef((props, ref) => {
return (
<div>
<input ref={ref} />
</div>
);
});
//parent
class Parent extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
focusHandler = () => {
this.inputRef.current.focus();
};
render() {
return (
<div>
<Child ref={this.inputRef} />
<button onClick={this.focusHandler}>focus Input</button>
</div>
);
}
}
@react-ram
Copy link
Author

react-ram commented Jul 21, 2019

Ref forwarding is a technique for automatically passing a ref through a component to one of its children.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment