How we can use pipes in React JavaScript? How we can use pipes in React JavaScript? angular angular

How we can use pipes in React JavaScript?


There are simply no pipes, because anything evaluated in the brackets is considered plain JavaScript. Because this is evaluated as plain javascript, there is simply no need for pipes. If this.state.variable is a string, I can use the .toUpperCase() prototype to display the string in all uppercase:

{this.state.variable.toUpperCase()}

This would be functionally equivalent to UpperCasePipe:

{{variable | uppercase}}

It's easy enough to just create a wrapper function, and use that. For example, if you wanted to create a custom function to uppercase just the first letter, we can use this function from here:

function capitalizeFirstLetter(string) {    return string.charAt(0).toUpperCase() + string.slice(1);}

We then would call it like so:

{capitalizeFirstLetter(this.state.variable)}


Expressions within {} in JSX are just plain JavaScript. | is bitwise OR. There are no Angular-like "pipes". A JavaScript function achieves the same thing, though.

Alternatively, to get memoisation, try the new useMemo() hook


In the simplest case, you just need to call a function in the "template" (although there are no templates in React: it's just JSX syntax, a sugar on top of existing standard, in order to allow you to write XML-like code for calling a function in the middle of regular JavaScript file).

So what would in Angular be a pipe with name set to 'uppercase', can in React be a simple function:

function uppercase (value: string) { return /* ... */ }  

In React, you'd just call this function in the middle of the "template" with no care in the world:

<div> { uppercase(value_expression) } </div>

But there's something that they don't tell you: Angular pipes are by default marked as pure functions and Angular doesn't re-run the pipe code unless its inputs change. With the React "equivalent" shown above, you don't get that. Instead, every time a component is re-rendered (which can be quite often, as often as typing or clicking anything in the app), the whole body of the function will be re-evaluated.

Now, for such a simple case as an uppercase pipe/function, that's not a big deal, but you might have some more complex calculations, or might have the same calculation repeated numerous times (such as in a large data table). In such cases, this is not an acceptable behavior.

Therefore, you'd need a caching or memoization strategy for your React functions which act as pipes in Angular. And, guess what, just like everything else in React, the library doesn't solve it for you, so you have to hunt down such a simple thing yourself, decide on which you want to use, install the package, read its docs, and use it.