Search code examples
javascriptreactjsfocusparent

How to focus input on a child component from parent?


I'm using React.forwardRef to set a ref on my Child component, like so:

const Input = React.forwardRef(
  ({ value, onChange, onKeyPress, placeholder, type, label, ref }) => (
    <div style={{ display: "flex", flexDirection: "column" }}>
      <input
        ref={ref}
        style={{
          borderRadius: `${scale.s1}rem`,
          border: `1px solid ${color.lightGrey}`,
          padding: `${scale.s3}rem`,
          marginBottom: `${scale.s3}rem`
        }}
        value={value}
        onChange={onChange}
        onKeyPress={onKeyPress}
        placeholder={placeholder ? placeholder : "Type something..."}
        type={type ? type : "text"}
      />
    </div>
  )
);

In the parent I use const ref = React.createRef() and then call it:

 onClick = () => {
    this.setState({ showOther: true });
    console.log(this.ref, "ref");
    this.ref.focus();
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.onClick}>Click me</button>
        <Input
          ref={ref}
          value={this.state.value}
          onChange={this.handleChange}
          onKeyPress={this.handleKeyPress}
          placeholder="Type something..."
        />
      </div>
    );
  }

What I get from the console is this:

Object {current: null} current: null "ref"

My questions:

  • Why is this null?
  • How do I focus the input?

Codesandbox


Solution

  • Based on your sandbox, You use ref from outside class Component instead this.ref. Just change it from

    <Input
      ref={ref}
    />
    

    into this

    <Input
      ref={this.ref}
    />
    

    and inside onClick function to be like this

     onClick = () => {
        this.setState({ showOther: true });
        console.log(this.ref, "ref");
        this.ref.current.focus(); // change it
      };
    

    this is the working codesandbox, enjoy!