Last active
July 21, 2019 13:45
-
-
Save react-ram/a0164a14f9df0f053887e98f4348e132 to your computer and use it in GitHub Desktop.
EXAMPLE FOR : forwarding Ref's
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
function App() { | |
return ( | |
<div className="App"> | |
<Parent /> | |
</div> | |
); | |
} |
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
//child | |
const Child = React.forwardRef((props, ref) => { | |
return ( | |
<div> | |
<input ref={ref} /> | |
</div> | |
); | |
}); |
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
//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> | |
); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ref forwarding is a technique for automatically passing a ref through a component to one of its children.