简体   繁体   中英

How to export functions and make them reusable in javascript / reactjs

I have a piece of code where I use it almost in all my components and is working perfectly fine but I would like to make it reusable.

I tried to export it in a different file then imported and pass the arguments on the function but it didn't work.

The searchTerm is simply an input where I set the state to the value of the input.

const data = [
  {
    name: "User"
    email: "user@email.com"
    phone: 0000000
    gender: "male"
    notes: "some notes"
    birthday: "00/00/0000"
  }
]

What I have and want to reuse:

let filteredData = []

if (clients.length > 0) {
  filteredData =
    data.filter(d=> Object.values(d).join(' 
    ').toLowerCase().match(searchTerm.toLowerCase()))
}

What I tried:

export function tableFilter(data, searchTerm) {
  if (data.length > 0) {
    return data.filter(d => Object.values(d).join(' 
    ').toLowerCase().match(searchTerm.toLowerCase()))
  }
}

The expected result's are to use the function in all my components without rewriting it. What I am getting now is no data at all.

The solution it was very simple :

export function tableFilter(data, searchTerm) {
  let filteredData = []
  // the if check is not necessary 
  if (data.length > 0) {
    filteredData = data.filter(d => Object.values(d).join(' 
    ').toLowerCase().match(searchTerm.toLowerCase()))
  }
  return filteredData
}

Why not create the function in the root component and pass it to all the child components that use the functionality.

class App extends React.Component {
  tableFilter(data, searchTerm) {
      if (data.length > 0) {
         return data.filter(d => Object.values(d).join('')
                                            .toLowerCase()
                                            .match(searchTerm.toLowerCase()))
       }
  }
  render() {
    return (<div>
             <Child1 myfilter={this.tableFilter} />
             <Child2 myfilter={this.tableFilter} />
             <Child3 myfilter={this.tableFilter} />
             <Child4 myfilter={this.tableFilter} />
             ...
           </div>);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM