R
R
Richard Millie2020-02-03 13:16:22
JavaScript
Richard Millie, 2020-02-03 13:16:22

What is the correct way to refer to the pointer to the current element of the array?

There is a code that displays a list of posts:

import React from "react";


type respX = {
    "id": any,
    "userId": any,
    "title": any,
    "body": any,
}

interface PropsI {
}

interface StateI {
    data: respX[];
}

export class ComponentPostList extends React.Component<PropsI, StateI> {

    state: StateI = {data: []}

    async componentDidMount() {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/`);
        const json = await response.json();
        this.setState({data: json});
    }


    render() {
        return (
            <div className="About">
                {this.state.data.map(el => (
                    <li key={el.id}>
                        {el.title}
                    </li>
                ))}
            </div>
        );
    }
}

How can I print to the console the id of the element we clicked on?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
re1mond, 2020-02-03
@comewithme38

{this.state.data.map(el => (
                    <li key={el.id} onClick = {() => {console.log(el.id)}}>
                        {el.title}
                    </li>
                ))}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question