score:8

Accepted answer

The way I see it, you need to either duplicate your starIcon boolean in an array that has the same length as your data array, or integrate your boolean in your data array. Here's a proposition for the second option :

import React from 'react';
import StarBorder from '@material-ui/icons/StarBorder';
import Star from '@material-ui/icons/Star';
import axios from 'axios';

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        }
    }

    componentDidMount() {

        axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true')
            .then(res => {
                const data = res.data;
                this.setState({  data: data.map(x => ({...x, starIcon: true}) ) })
            })
    }

    handleClick = (i) => {
        this.setState(prevState => ({
          data: prevState.data.map((x, key) => (key === i ? {...x, starIcon: !x. starIcon} : x) )
        }));
      }

    render() {
        return (
        <div>
            <table border="1">
                <thead>
                    <tr>
                    <td>Rank</td>
                    <td>Name</td>
                    <td>Price</td>
                    </tr>
                </thead>
                <tbody>
                {this.state.data.map((n, i) => {
                    return (
                        <tr>
                        <td> <span onClick={() => this.handleClick(i)}> {n.starIcon ? <StarBorder/> : <Star /> } </span> </td>
                        <td>{n.name}</td>
                        <td>{n.current_price}</td>
                        </tr>
                    );
                    })}
                </tbody>
            </table>
        </div>
        );
    }
}

export default Test;

Hope it helps


Related Query

More Query from same tag