Pouya Ataei
Pouya Ataei

Reputation: 2169

Law-abiding React Hooks

I'm looking for a way to use my custom hook inside the map function as I render the components...

FYI, I'm totally aware of the hooks rule " Don’t call Hooks inside loops, conditions, or nested functions. " But I believe there is a way around it without breaking the rule....

Here's some more info:

We've got a custom hook called useCommaHook as below:

export const useCommaHook = price => {
  const priceArray = price.toString().split("")
  const beforeComma = priceArray.slice(0, 1).join("")
  const afterComma = priceArray.slice(1, 4).join("")
  return `${beforeComma},${afterComma}`
}

Which can be used to add comma for currencies while rendering:

const renderTours = data => {
    return data.map((element, idx) => {
        return (
          <span className="filtered-tour__description-price">
            *** --> We'd like to use our hook here to get comma for every price in the loop***
            {`from ${element.node.priceFrom}`
          </span>
        )
    })
}

As commented above we'd like to apply that filter to all the node prices in our array.

How would you go about solving such an issue ? any idea is appreciated.

Upvotes: 1

Views: 63

Answers (2)

ANIK ISLAM SHOJIB
ANIK ISLAM SHOJIB

Reputation: 3238

Building your own Hooks lets you extract component logic into reusable functions. But here your useCommaHook is a simple functional component its function is to

return `${beforeComma},${afterComma}`

You didn't even use native hooks inside useCommaHook and there is not state in your function and so State Hook is not applicable in your code.

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138257

useCommaHook is not a hook! It doesn't call any of the native hooks (useState, ...). Therefore the rules of hooks do not apply.

Upvotes: 4

Related Questions