-
Notifications
You must be signed in to change notification settings - Fork 4
/
Focus.js
48 lines (38 loc) · 1.19 KB
/
Focus.js
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
47
48
import React from 'react';
import { createRoot } from 'react-dom/client';
class Input extends React.PureComponent {
render() {
let {forwardedRef, ...otherProps} = this.props;
return <input {...otherProps} ref={forwardedRef} />;
}
}
const TextInput = React.forwardRef((props, ref) => {
return <Input {...props} forwardedRef={ref} />
});
class FocusableInput extends React.Component {
ref = React.createRef()
render() {
return <TextInput ref={this.ref} />;
}
// When the focused prop is changed from false to true,
// and the input is not focused, it should receive focus.
// If focused prop is true, the input should receive the focus.
// Implement your solution below:
componentDidUpdate(prevProps) {
if (prevProps.focused != this.props.focused && this.props.focused) {
this.ref.current.focus();
}
}
componentDidMount() {
if (this.props.focused) {
this.ref.current.focus();
}
}
}
FocusableInput.defaultProps = {
focused: false
};
const App = (props) => <FocusableInput focused={props.focused} />;
document.body.innerHTML = "<div id='root'></div>";
const root = createRoot(document.getElementById("root"));
root.render(<App />);