Search code examples
reactjsjsxes6-map

Why does moving the array map of props outside the render function not work in React?


The example below works just fine, I'm mapping the props array in the render function.

class Calendar extends Component {
    render(){
        return(
           <div>
                { this.props.events.map((event, idx) => {
                    return <li key={idx}>{event.title}</li>
                })}

            </div>
        );
    }
}

But when I move the array map into another function is no longer works.

class Calendar extends Component {

    handleEvents(){
        this.props.events.map((event, idx) => {
            return <li key={idx}>{event.title}</li>
        })
    }
    render(){
        return(
            <div>
                { this.handleEvents() }
            </div>
        );
    }
}

Any help would be appreciated.


Solution

  • I guess you just forgot to return from your function

    class Calendar extends Component {
    
        handleEvents(){
            // here.
            return this.props.events.map((event, idx) => {
                return <li key={idx}>{event.title}</li>
            })
        }
        render(){
            return(
                <div>
                    { this.handleEvents() }
                </div>
            );
        }
    }