Kamalakannan J
Kamalakannan J

Reputation: 2998

AngularJS filter in React Component

I'm totally new to ReactJS, but I love its awesome performance over AngularJS. My question is, in AngularJS we use filters in the view templates before rendering the expression or model, how we can achieve that in ReactJS. Now I'm trying to replace few view parts as React Components(still it is in AngularJS).

For example, now my below angular code works fine to render a emoticon in p tag,

<div ng-init='{messageWithAngularEmoji = "This is a :smile:"}'>

     <p ng-bind="{messageWithAngularEmoji | emoji | to_trusted }"></p>

</div>

In the above example you can see I had used two filters: emoji and to_trusted. How can I achieve this in ReactJS ?

Note: I can't rewrite those filters in React.

Upvotes: 7

Views: 6239

Answers (3)

Michael J. Calkins
Michael J. Calkins

Reputation: 32663

This question has already been answered correctly. I want to provide a different perspective using ES6 for any future readers like myself.

Writing a currency filter using ReactJS

currency.js

export default function(value, decimalPosition = 2) {
    return '$' + value
        .toFixed(decimalPosition)
        .replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
}

component.js

export default function FundsAmount() {
    let amount = 2345.43

    return (
        <span>{ currency(amount) }</span>
    )
}

This will output:

$2,345.43

Upvotes: 3

Brigand
Brigand

Reputation: 86260

In angular a filter is just a very contrived way to call a function.

module.filter('emoji', function(){
  return function(x){
    /* stuff */
  };
});

Becomes

function emoji(x){
    /* stuff */
};

React is just JavaScript, so you define functions and you use them.

<p>{to_trusted(emoji(messageWithAngularEmoji))}</p>

You probably don't need to_trusted because that's likely referring to SCE, which is part of angular.

Upvotes: 5

daniula
daniula

Reputation: 7028

After a little search I found the way to retrieve angular filter outside of angular, so in your case this should do a trick:

render: function() {
    var injector = angular.element("div[ng-controller]").injector(); 
    var emoji = injector.get('emojiFilter'); 
    var message = 'This is a :smile:';
    return (
        <div>
            <p>{emoji(message)}</p>
        </div>
    );
}

Upvotes: 5

Related Questions