2

I am trying to apply this example to my own code, but it seems that "ref" properties are obsolete in this form. Can anyone help me with this code? Right now i am getting "Cannot read property 'focus' of undefined", when clicking on filter

const data = [{
  key: '1',
  name: 'John Brown',
  age: 32,
  address: 'New York No. 1 Lake Park',
}, {
  key: '2',
  name: 'Joe Black',
  age: 42,
  address: 'London No. 1 Lake Park',
}, {
  key: '3',
  name: 'Jim Green',
  age: 32,
  address: 'Sidney No. 1 Lake Park',
}, {
  key: '4',
  name: 'Jim Red',
  age: 32,
  address: 'London No. 2 Lake Park',
}];

class App extends React.Component {
  state = {
    searchText: '',
  };

  handleSearch = (selectedKeys, confirm) => () => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  }

  handleReset = clearFilters => () => {
    clearFilters();
    this.setState({ searchText: '' });
  }

  render() {
    const columns = [{
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
        <div className="custom-filter-dropdown">
          <Input
            ref={ele => this.searchInput = ele}
            placeholder="Search name"
            value={selectedKeys[0]}
            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
            onPressEnter={this.handleSearch(selectedKeys, confirm)}
          />
          <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>Search</Button>
          <Button onClick={this.handleReset(clearFilters)}>Reset</Button>
        </div>
      ),
      filterIcon: filtered => <Icon type="smile-o" style={{ color: filtered ? '#108ee9' : '#aaa' }} />,
      onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
      onFilterDropdownVisibleChange: (visible) => {
        if (visible) {
          setTimeout(() => {
            this.searchInput.focus();
          });
        }
      },
      render: (text) => {
        const { searchText } = this.state;
        return searchText ? (
          <span>
            {text.split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i')).map((fragment, i) => (
              fragment.toLowerCase() === searchText.toLowerCase()
                ? <span key={i} className="highlight">{fragment}</span> : fragment // eslint-disable-line
            ))}
          </span>
        ) : text;
      },
    }, {
      title: 'Age',
      dataIndex: 'age',
      key: 'age',
    }, {
      title: 'Address',
      dataIndex: 'address',
      key: 'address',
      filters: [{
        text: 'London',
        value: 'London',
      }, {
        text: 'New York',
        value: 'New York',
      }],
      onFilter: (value, record) => record.address.indexOf(value) === 0,
    }];
    return <Table columns={columns} dataSource={data} />;
  }
}

ReactDOM.render(<App />, mountNode);

code that I am trying to execute https://hastebin.com/yipusowala.coffeescript

{
        title: 'Rider',
        key: 'rider',
        width: '25%',
        dataIndex: 'rider.name',
        filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
            <div className="custom-filter-dropdown">
                <Input
                    ref={(input) => { this.searchInput= input; }}
                    placeholder="Search name"
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={this.handleSearch(selectedKeys, confirm)}
                />
                <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>Search</Button>
                <Button onClick={this.handleReset(clearFilters)}>Reset</Button>
            </div>
        ),
        onFilter: (value, record) => record.rider.name.toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
                setTimeout(() => {
                    this.searchInput.focus();
                });
            }
        },
        render: (text) => {
            const {userFilterText} = this.state.userFilterText;
            return userFilterText ? (
                <span>
                    {text.split(new RegExp(`(?<=${userFilterText})|(?=${userFilterText})`, 'i')).map((fragment, i) => (
                        fragment.toLowerCase() === userFilterText.toLowerCase()
                            ? <span key={i} className="highlight">{fragment}</span> : fragment // eslint-disable-line
                    ))}
                </span>) : text;
        }
    },
mlynarz
  • 21
  • 5

1 Answers1

0

Your code seems just fine
(apart from this object destructuring:
const {userFilterText} = this.state.userFilterText;
which I'm guessing is a typo)

I created this sandbox based on the example you described and the ref for the <Input /> component as well as the .focus() trigger - seem to be working fine. (check out the console and you can see the Input ref being logged)

Hope this helps :)

itaydafna
  • 1,968
  • 1
  • 13
  • 26
  • when I try to use it with export default App, the problem occurs anyway – mlynarz Sep 05 '18 at 16:07
  • I mean i am using this form class HorseList extends Component { } export default HorseList; – mlynarz Sep 05 '18 at 18:24
  • can you fork the [snadbox](https://codesandbox.io/s/43483n37r4) and share the link in order to show where your code breakes? – itaydafna Sep 05 '18 at 19:45
  • https://codesandbox.io/s/5y98w1247l here you go, but sandbox seems not to work with it at all, it doesnt even compile – mlynarz Sep 05 '18 at 20:37
  • if I try to use your code with export default, it doesnt focus anyway – mlynarz Sep 05 '18 at 20:53
  • I made a few minor changes and managed to get your `` component to render in the [sandbox](https://codesandbox.io/s/p9yqv2ml6m) - you still need to add data to the tabe - but the focus on the rider column is working fine – itaydafna Sep 05 '18 at 21:30
  • still, not working. I guess it might be something with react version, I found this https://stackoverflow.com/questions/35230020/this-refs-something-returns-undefined – mlynarz Sep 06 '18 at 06:27
  • (my version of react 16.4.1) – mlynarz Sep 06 '18 at 06:39
  • just to make sure I understand correctly what you are trying to achive - in the last [sandboox](https://codesandbox.io/s/p9yqv2ml6m) I sent - do you see the focus working or is there something else there which you expect to happen which isn't working? – itaydafna Sep 06 '18 at 07:03
  • on sandbox it is working, when I paste the code into IntelliJ I get the same error and the searchInput is null – mlynarz Sep 06 '18 at 08:01
  • maybe you should try creating the project again from scratch using [create-react-app](https://github.com/facebook/create-react-app) and just paste the code you have in there - this will help insure all the versions are compatible – itaydafna Sep 06 '18 at 08:48
  • 1
    seems that npm update solved the problem... so basically I caused the problem :) – mlynarz Sep 06 '18 at 09:08