ReactJS toLowerCase is not a function
Asked Answered
B

3

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}/>
    });
Bogor answered 7/2, 2016 at 0:27 Comment(6)
What value does props.filterText have?Slaton
Is episode.title a String? try episode.title.toString().toLowerCase() or console.log its' value to the console.Tondatone
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 undefinedLipolysis
@adam: would undefined cause a RefError "undefined has no property toLowerCase"... ?Archaism
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.Lipolysis
@Archaism - 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.Lipolysis
N
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;
Naphthol answered 2/9, 2016 at 21:18 Comment(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.Calvary
I
0

I think I found the problem :)

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

Implement answered 2/8, 2021 at 16:53 Comment(1)
I had this problem again 2 times.Jocose
C
-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 '';
    }
})
Calvary answered 2/8, 2017 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.