React Test: I'm supposed to use hooks, but I can't import them?

I’m studying for a React test. (This question is free and public practice question, so I’m not cheating on a job interview).

Prompt

Finish the FocusableInput component so that the input element automatically receives focus on the first render if the shouldFocus prop is true.

The component should use React Hooks.

Starter Code

// React is loaded and is available as React and ReactDOM
// imports should NOT be used
const FocusableInput = (props) => {
  // Write your code here
  return <input />;
};

document.body.innerHTML = "<div id='root' />";
ReactDOM.render(<FocusableInput shouldFocus={true} />, document.getElementById("root"));
setTimeout(() => console.log(document.getElementById("root").innerHTML));

My first answer

const FocusableInput = (props) => {
  if (props.shouldFocus) {
    return <input autoFocus />
  } else {
    return <input />
  }
};

This passes the check for "The input is focused only if shouldFocus is true"
and "The input is focused only on the first render"
but fails the check for "The component uses React Hooks"

My answer with hooks

const FocusableInput = (props) => {
  const inputRef = useRef();

  useEffect(() => {
    if (props.shouldFocus) {
      inputRef.current.focus();
    }
  }, [props]);
  
  return <input ref={inputRef} />;
  
};

This works on my machine, but fails all three checks on the test because

Line 6: Uncaught ReferenceError: useRef is not defined

Out of curiosity, I tried importing useRef, even though the instructions told me not to. Of course,

Cannot use import statement outside a module

Thank you in advance for any insight.

>Solution :

Because the starter code says

// React is loaded and is available as React and ReactDOM

// imports should NOT be used

Imports aren’t permitted, but because you have access to the React object, you don’t need any more imports – all hook functions are available on React itself. You can change

const inputRef = useRef();

to

const inputRef = React.useRef();

This is the same technique one must use when using hooks with Babel Standalone (which runs completely on the client side, without modules or imports of any kind).

const { useState, useEffect } = React;
const App = () => {
    const [state, setState] = useState('init');
    useEffect(() => {
      setTimeout(() => {
        setState('later');
      }, 1000);
    }, []);
    return <div>{state}</div>;
};

ReactDOM.createRoot(document.querySelector('.react')).render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>

Leave a Reply