forked from vasanthk/react-bits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
31.reaching-into-a-component.jsx
46 lines (42 loc) · 1.02 KB
/
31.reaching-into-a-component.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Reaching into a Component
*
* Accessing a component from the parent.
* eg. Autofocus an input (controlled by parent component)
*
* @Reference:
* https://hackernoon.com/10-react-mini-patterns-c1da92f068c5
*/
// Child Component
// An input component with a focus() method that focuses the HTML element
class Input extends Component {
focus() {
this.el.focus();
}
render() {
return (
<input
ref={el=> { this.el = el; }}
/>
);
}
}
// Parent Component
// In the parent component, we can get a reference to the Input component and call its focus() method.
class SignInModal extends Component {
componentDidMount() {
// Note that when you use ref on a component, it’s a reference to
// the component (not the underlying element), so you have access to its methods.
this.InputComponent.focus();
}
render() {
return (
<div>
<label>User name:</label>
<Input
ref={comp => { this.InputComponent = comp; }}
/>
</div>
)
}
}