1

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: "[email protected]"
    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.

6
  • What do you mean by "did not work"? Commented Aug 29, 2019 at 7:11
  • @EriksKlotins I mean I cannot filter the data and I cannot see the full list of the data. Commented Aug 29, 2019 at 7:13
  • 2
    please post sample input data and searchterm Commented Aug 29, 2019 at 7:20
  • stackoverflow.com/questions/38402025/… may be helpful Commented Aug 29, 2019 at 7:27
  • You can remove the 0 check because filter will just return an empty array if the data is empty. Commented Aug 29, 2019 at 7:35

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.