Reaching into a Component

Accessing a component from the parent.
eg. Autofocus an input (controlled by parent component)

Child Component

An input component with a focus() method that focuses the HTML element

  1. class Input extends Component {
  2. focus() {
  3. this.el.focus();
  4. }
  5. render() {
  6. return (
  7. <input
  8. ref={el=> { this.el = el; }}
  9. />
  10. );
  11. }
  12. }

Parent Component

In the parent component, we can get a reference to the Input component and call its focus() method.

  1. class SignInModal extends Component {
  2. componentDidMount() {
  3. // Note that when you use ref on a component, it’s a reference to
  4. // the component (not the underlying element), so you have access to its methods.
  5. this.InputComponent.focus();
  6. }
  7. render() {
  8. return (
  9. <div>
  10. <label>User name:</label>
  11. <Input
  12. ref={comp => { this.InputComponent = comp; }}
  13. />
  14. </div>
  15. )
  16. }
  17. }

Reference: