1

I want to access formatted as well as "untouched" data in a custom filter but I was unsuccessful:

accessor: row => {
    row.ageFormatted = row.age + " yrs";
    return row.age;
},
Cell: row => (
    <div style={{ textAlign: "center" }}>
        {row.original.ageFormatted}
    </div>
),
filterMethod: (filter, row) => {
    return (
        row.age + "" === filter.value ||
        row.ageFormatted.contains(filter.value)
    );
}

From my code example in a sandbox: https://codesandbox.io/s/react-table-custom-filtering-j90oh (a fork of the official react-table example for custom filtering). The user should be able to filter for a number or a string like "3 y".

How can I achieve this?

2 Answers 2

4

You could calculate all formated values into an Object on componentDidMount, save it into the state, and use it instead of calculating it every time you use the filter. See my working solution here: https://codesandbox.io/s/react-table-custom-filtering-84lxw

Also, your row.ageFormatted.contains(filter.value) comparison is wrong. The correct way to check if a String contains a Substring is .includes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

Sign up to request clarification or add additional context in comments.

Comments

2

row seems to not retain added data. So instead of depending on side-effects, rather use a helper function to generate row.ageFormatted from row.age in the filterMethod().

It is often better to store less redundant data and rather generate derivated values from the data you really need to store. Having less redundancy in your data means you have to synchronise a lot less. Especially if the difference between the two fields is as trivial as in the given example.

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.