1

I'm new to React and having trouble connecting the values of 6 buttons created with a map() function on an array to 6 categories from an API request.

I tried to define a category in the state of the class component but I'm unsure how to make the name of the button dynamically match the categories of the API.

Here's my code so far :

import axios from 'axios';
import Card from 'react-bootstrap/Card';
import Button from 'react-bootstrap/Button';
import ButtonCategory from '../ButtonCategory/ButtonCategory';
import CategoriesCard from '../CategoriesCard/CategoriesCard';
import WinnerCard from '../WinnerCard/WinnerCard'
import './ButtonsCategories.css'

export class ButtonsCategories extends Component {
    state = {
        category: []

    }

    handleClick = () => {
        axios.get('http://api.nobelprize.org/2.0/nobelPrizes?limit=2&sort=desc&nobelPrizeCategory=' + this.state.category + '&format=json&csvLang=en')
            .then(res => {
                const categoryData = res.data.nobelPrizes;
                console.log(categoryData)
                // console.log("CATEGORY", categoryData?.category?.en)

                this.setState({
                    category: this.state.category
                })
            }).
            catch(err => console.log(err))
    };

    render() {

        //BUTTONS CATEGORIES
        const allCategoriesButtons = ["Physics", "Chemistry", "Medicine", "Literature", "Peace", "Economics"];

        const allCatMap = allCategoriesButtons.map((button) => {
            return < ButtonCategory
                key={button.toString()}
                value={button}
                name={button}
                // valueOf={this.state.category}
                onClick={this.handleClick}
            />
        })


        return (
            <div className="container">
                <div className="btn-group w-100">
                    {allCatMap}
                </div>
            </div>
        )
    }
}

export default ButtonsCategories;

It seems simple, yet I can't think of how to change this.state.category by connecting it to the buttons.

Any help is very welcome

Etwck_380
  • 17
  • 1
  • 5

1 Answers1

1

I think the issue here is you are using the same function to handle the different buttons, but the handleClick function does not actually know which button was pressed.

In the allCatMap, change the onClick to get which button is pressed:

onClick={e => this.handleClick(e.target.value)}

And then update the handleClick declaration (and the api call):

handleClick = (buttonValue) => {
    axios.get('http://api.nobelprize.org/2.0/nobelPrizes?limit=2&sort=desc&nobelPrizeCategory=' + buttonValue + '&format=json&csvLang=en')
Jason Kennaly
  • 622
  • 1
  • 5
  • 9