Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...