N
N
Nikolai Eremeev2018-07-03 17:01:09
React
Nikolai Eremeev, 2018-07-03 17:01:09

How to call class method in react from map function in render?

How do I call the deletePoint function from the map function in the render method? Thank you for your responses!
Error text now: TypeError: Cannot read property 'deletePoint' of undefined

class SideBar extends Component {

    deletePoint = (obj) => { ... }

    render() {
        const points = this.props.markers;
        const point = points.map(function (obj, index) {
            return (
                <li key={index}>
                    {obj.address}
                    <button onClick={this.deletePoint(obj)}>Удалить точку</button>
                </li>
            )
        })

        return (
            <div>
                <div>
                    <ol>{point}</ol>
                </div>
            </div>
        )
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-07-03
@Nere

Replace the callback with an arrow function:

const point = points.map((obj, index) => (
  <li key={index}>
    {obj.address}
    <button onClick={this.deletePoint(obj)}>Удалитьточку</button>
  </li>
));

N
Nikolay Eremeev, 2018-07-03
@Nere

Thank you! Understood))

class SideBar extends Component {


    deletePoint = (obj) => {
        
        const text = 'Вы хотите удалить точку маршрута \'' + obj.address + '\'?';
        const result = window.confirm(text);

        if(result) {

            const markers = this.props.markers,
                routes = this.props.routes;

            for (let i = 0; i < markers.length; i++) {
                if (markers[i].address === obj.address) {
                    markers.slice(i,1);
                    routes.slice(i,1);
                }
            }

            this.props.deleteRoute(markers, routes)
        }
    }


    render() {
        const points = this.props.markers;
        const point = points.map((obj, index) => (
                <li key={index}>
                    {obj.address}
                    <button onClick={this.deletePoint.bind(this, obj)}>Удалить точку</button>
                </li>
            )
        )

        return (
            <div>
                <div>
                    <ol>{point}</ol>
                </div>
            </div>
        )
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question