Search code examples
reactjsantdreact-typescript

React Ant design 4 Input search display table data


I'm tried to create Ant design 4 input search to filter data , Name and age, when i search name or age wanna display table data but its not working anyone know how to do that correctly

stazkblitz here

code here

const columns = [
  {
    title: "Name",
    dataIndex: "name",
    key: "name",
    render: text => <a>{text}</a>
  },
  {
    title: "Age",
    dataIndex: "age",
    key: "age"
  }
];

const data = [
  {
    key: "1",
    name: "John Brown",
    age: 32
  },
  {
    key: "2",
    name: "Jim Green",
    age: 42
  },
  {
    key: "3",
    name: "Joe Black",
    age: 32
  }
];
const onSearch = value => console.log(value);
ReactDOM.render(
<div><Search
      placeholder="input search text"
      allowClear
      enterButton="Search"
      size="large"
      onSearch={onSearch}
    />
    <br/>
       <br/>   <br/>
    <Table columns={columns} dataSource={data} /></div>,
    document.getElementById('container')
 
);

Thanks


Solution

    • you need to extract your code to create a component;
    • create a filterInput state with React.useState, that holds inputSearch value. React.useState returns an array, where the first value is state, and second is a function to update that state value;
    • create a function filterData based on filterInput to filter your data table;

    for filterData I return all data if it's empty. I check if is not a number to decide how to filter, by name or age.

    function App() {
      const [filterInput, setFilterInput] = React.useState('')
      const filterData = () => {
        if(filterInput === '') return data
    
        if(isNaN(filterInput)) {
          return data.filter(({ name }) => name.includes(filterInput))
        }
        return data.filter(({ age }) => age === +filterInput)
      }
    
      return <div><Search
          placeholder="input search text"
          allowClear
          enterButton="Search"
          size="large"
          onSearch={setFilterInput}
        />
        <br/>
           <br/>   <br/>
        <Table columns={columns} dataSource={filterData()} /></div>
    }
    
    ReactDOM.render(
      <App />
    ,
        document.getElementById('container')
     
    );
    

    sample code