'TestDome - REACT - 1. Focus
The TextInput component renders an input element in the DOM and accepts a ref that is forwarded to that input element. Finish the FocusableInput component:
The component should accept a focused prop. When the focused prop is changed from false to true, and the input is not focused, it should receive the focus. If on mounting the focused prop is true, the input should receive the focus.
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) {}
componentDidMount() {}
}
FocusableInput.defaultProps = {
focused: false
};
const App = (props) => <FocusableInput focused={props.focused} />;
document.body.innerHTML = "<div id='root'></div>";
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);```
> I don't get what they want me to do.. does anyone have the solution
> for this?
>
> https://www.testdome.com/d/react-js-interview-questions/304
Solution 1:[1]
the functions componentDidUpdate & ComponentDidMount should be like this:
componentDidUpdate(prevProps) {
if(prevProps.focused != this.props.focused && this.props.focused){
this.ref.current.focus();
}
}
componentDidMount() {
if(this.props.focused){
this.ref.current.focus();
}
}
}
Solution 2:[2]
This worked for me.
componentDidUpdate(prevProps) {
this.ref.current.focus();
}
componentDidMount() {
if (this.props.focused) {
this.ref.current.focus();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Claudio Moscoso |
| Solution 2 | Anita Jayana |
