1

I found this great method on Stackoverflow to convert duration from ss into hh.mm.ss and I tried to call it within the render () section of the page. Many attempts, but not yet successful. I think I am missing something in the syntax of the arrow function, but can't find out what.

This is the method I slightly edited for my purpose:

formatTime(duration) {
    d = Number(duration);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
    return hDisplay + mDisplay + sDisplay;
    }

And this is my render() section, where I would like to call formatTime(), passing song.duration as an argument of the method (full code here):

render() {
     return (

//[...] 

     <td {() => this.formatTime(song.duration)}> 
     {formatTime(song.duration)} </td>

//[...] 

}
user3926863
  • 325
  • 4
  • 13

1 Answers1

0

Write it like this:

<td> {this.formatTime(song.duration)} </td>

Because of the following reasons:

1- Its a class method so you need to use this.functionName() to access the function.

2- You are normally calling the function and it is returning some content/value which you want to render so arrow function is not required.


Check this answer for more details about when javascript bind or arrow function is necessary

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
  • thank you and great link! I'm still getting an error "'d' is not defined" ... I assume this is related to passing the argument. I tried to put `song.duration` instead of `duration` as an argument, but I am still getting the error. – user3926863 Mar 02 '19 at 13:58
  • 1
    its because you are directly assigning value to variable d without declaring it. use this line: `var d = Number(duration);`, in the answer from where you copied that snippet, `d` is a function parameter thats why no declaration. – Mayank Shukla Mar 02 '19 at 14:05