Search code examples
reactjsantdalgolia

Cannot read property 'focus' of null error when extracting component


I would like to implement Algolia search with Ant Design Autocomplete. But I get Cannot read property 'focus' of null error when I try to extract the SearchInput component (without extraction, i. e. when I leave it in the same file, it works fine). Here is the working code:

import React, { useState } from 'react'
import { AutoComplete, Input } from 'antd'

const SearchAutocomplete = connectAutoComplete(
  ({ hits, currentRefinement, refine }) => {

    ...

    return (
      <AutoComplete
        options={options}
        onSelect={onSelect}
        onSearch={handleSearch}
        open={open}
      >
        <Input
          value={currentRefinement}
          onChange={e => refine(e.currentTarget.value)}
        />
      </AutoComplete>
    );
  }
);

But when I move Input to a separate component like this it doesn't work:

import React, { useState } from 'react'
import { AutoComplete } from 'antd'
import SearchInput from './SearchInput'

const SearchAutocomplete = connectAutoComplete(
  ({ hits, currentRefinement, refine }) => {

    ...

    return (
      <AutoComplete
        options={options}
        onSelect={onSelect}
        onSearch={handleSearch}
        open={open}
      >
        <SearchInput value={currentRefinement} onChange={e => refine(e.currentTarget.value)}/>
      </AutoComplete>
    );
  }
);

And the SearchInput component itself:

import React from 'react'
import { Input } from 'antd'

const SearchInput = props => {
  const { value, onChange} = props;

  return (
    <Input
      value={value}
      onChange={onChange}
    />
  )
}

Here is the link to codesandbox with the extracted component. How can I fix this error?


Solution

  • Adding React.forwardRef() to SearchInput solved the issue:

    const SearchInput = React.forwardRef((props, ref) => {
      const { onChange } = props;
    
      return (
        <Input.Search
          onChange={onChange}
          ref={ref}
        />
      )
    })