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