Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

reactjs - 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

question from:https://stackoverflow.com/questions/65850635/react-ant-design-4-input-search-display-table-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...