17

I am doing a comparison by converting my text to lowercase and comparing its index to -1, in order to have some value to the particular field in ReactJS, but I am getting this error in JavaScript console:

Uncaught TypeError: props.filterText.toLowerCase is not a function

var props = this.props;
var rows = this.props.episodes
    .filter(function(episode){
        return episode.title.toLowerCase().indexOf(props.filterText.toLowerCase()) > -1;
    })
    .map(function(episode){
       return <EpisodeRow key={episode.title} episode={episode}/>
    });
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
MaxWorld
  • 727
  • 2
  • 8
  • 11
  • 1
    What value does props.filterText have? – nnnnnn Feb 07 '16 at 00:29
  • 5
    Is `episode.title` a String? try episode.title.toString().toLowerCase() or console.log its' value to the console. – Chris Feb 07 '16 at 00:30
  • 1
    This is a pretty straightforward error - `props.filterText` is not a string. Just do a `console.log` inside your filter loop of `props.filterText` and you'll see it's not a string. My guess is that it will be `undefined` – Adam Jenkins Feb 07 '16 at 00:46
  • @adam: would undefined cause a RefError "undefined has no property toLowerCase"... ? – dandavis Feb 07 '16 at 00:48
  • Probably a very minor performance issue as well - but why do `.toLowerCase()` in a loop every time if you don't have to? `var filter = props.filterText.toLowerCase()` outside your filter function and do `indexOf(filter)` inside your function. – Adam Jenkins Feb 07 '16 at 00:51
  • @dandavis - you're right, it's not `undefined` it's just something that's not a string. Could be a function, number, boolean, but not a string. – Adam Jenkins Feb 07 '16 at 00:52

3 Answers3

31

Looks like Chris's comment is the correct answer:

If title is a string, use toString() before toLowerCase():

return episode.title.toString().toLowerCase().indexOf(props.filterText.toString().toLowerCase()) > -1;
ThePatelGuy
  • 1,844
  • 1
  • 19
  • 18
  • 1
    In my particular case, this solution rendered the text as "[Object] [Object]". You shouldn't be guessing when coding in a strongly-typed language. – HoldOffHunger Aug 02 '17 at 19:16
0

I think I found the problem :)

props.filterText is undefined. => The filterText:"" must be declared in the state before putting in props

-1

I think Adam's answer from the comments is actually correct, and turned out to solve my problem :

.filter(function(episode){
    if(episode.title) {
        return episode.title.toLowerCase().indexOf(props.filterText.toLowerCase()) > -1;
    } else {
        return '';
    }
})
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133