Ravenous Part 3, step 8 Help! TypeError: Cannot read property 'getSortByClass' of undefined

I am following the Ravenous video walkthrough and it differs from the lesson:
(https://www.codecademy.com/paths/web-development/tracks/front-end-applications-with-react/modules/ravenous-part-three/projects/setting-searchbar-state).

Following the video walkthrough in step 8, I get a “TypeError: Cannot read property ‘getSortByClass’ of undefined”. I have followed the code exactly and I don’t know what’s causing the error from LINE 31.

My SearchBar.js code is below:

import React from 'react';
import './SearchBar.css';

const sortByOptions = {
    'Best Match': 'best_match',
    'Highest Rated': 'rating',
    'Most Reviewed': 'review_count'
};

class SearchBar extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            term: '',
            location: '',
            sortBy: 'best_match'
        };        
    }

    getSortByClass(sortByOption){
    //    return (sortByOption === this.state.sortBy ) ? 'active' : '';
        if(sortByOption === this.state.sortBy){
            return 'active';
        } 
        return '';           
    }

    handleSortByChange(sortByOption){
        this.setState({ sortBy: sortByOption });
    }

    renderSortByOptions(){
        return Object.keys(sortByOptions).map(sortByOption =>{
            let sortByOptionValue = sortByOptions[sortByOption];
            return <li key={sortByOptionValue} className={this.getSortByClass(sortByOptionValue)}>{sortByOption}</li>;
        });
    }

    render(){
        return(
            <div className="SearchBar">
            <div className="SearchBar-sort-options">
                <ul>
                <this.renderSortByOptions />
                </ul>
            </div>
            <div className="SearchBar-fields">
                <input placeholder="Search Businesses" />
                <input placeholder="Where?" />
            </div>
            <div className="SearchBar-submit">
                <a>Let's Go</a>
            </div>
            </div>
        );
    }
}

export default SearchBar;

Hello there @dwilliams10, if you look at what the getSortByClass method is attached to, which is the this object. If the this object is undefined, it means that you forgot to bind your method. In the renderSortByOptions method though, the className attribute has to be set like this: className={this.getSortByClass(sortByOptionValue).bind(this, sortByOptionValue)
P.S. I recommend that you copy and paste this line to avoid errors in your code.

Hi, I input the code as you wrote it and I’m still getting the same error.

Your immediate issue is the way that you’re attempting to call this.renderSortByOptions in the JSX. You needed to use braces instead of using it like it was a html tag or component.

<ul>
{this.renderSortByOptions()}
</ul>
1 Like

That did it! Thank you so much!!