Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we can use pipes in React JavaScript?

In Angular we can create a custom pipe to change data format. For example, see the UpperCasePipe:

{{ value_expression | uppercase }} 

There doesn't appear to be pipes in React, so my question is: How can we use pipes in React?

like image 213
kamal aryal Avatar asked Feb 13 '19 11:02

kamal aryal


People also ask

How do you use pipes in React?

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).

What is pipe used for in HTML?

“A pipe is a way to write display-value transformations that you can declare in your HTML. It takes in data as input and transforms it to a desired output”.

How do you use React in JavaScript?

Create React App The create-react-app tool is an officially supported way to create React applications. Node.js is required to use create-react-app . Open your terminal in the directory you would like to create your application. create-react-app will set up everything you need to run a React application.

What is pipes in Angular js?

Pipes are simple functions to use in template expressions to accept an input value and return a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once.


1 Answers

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)} 
like image 136
ugh StackExchange Avatar answered Sep 20 '22 12:09

ugh StackExchange