I have such a project. Here I want the color to change when the button is clicked. The buttons are divided into categories. But there is such a problem that when I click, all the colors change. I just want to change the color of the button corresponding to the category I selected. How can I fix it?
import React, { useEffect, useState } from "react";
import SpinnerLoad from './components/SpinnerLoad'
import NewsItem from "./components/NewsItem";
import Category from "./components/data/Category"
const App = () => {
const [state, setState] = useState([]);
const [loading, setLoading] = useState(false)
const [btnColor, setBtnColor] = useState("black");
const setColor = () =>{
setBtnColor('red')
}
const fetchValue = (category) => {
localStorage.setItem("category", category);
fetch(`https://inshorts-api.herokuapp.com/news?category=${category}`)
.then(res => res.json())
.then(res => {
setState(res.data)
setLoading(true)
})
.catch((error) => console.log(error))
setLoading(false);
};
const CategoryButton = ({ category }) => (
<button onClick={() => { fetchValue(category); setColor() }}
style={{ textTransform: 'capitalize',color:btnColor }} >{category}</button>
);
useEffect(() => {
let categoryValue = localStorage.getItem("category") || "all" ;
fetchValue(categoryValue)
},[]);
return (
<>
<div className="header-bg">
<h1 className="mb-3">News</h1>
<div className="btns ">
{Category.map((value, index) => {
return <CategoryButton category={value} key={index} />;
})}
</div>
</div>
<div className="news">
<div className="container">
<div className="row">
{
!loading
? <SpinnerLoad/>
:
state.map((data,index) => {
return (
<NewsItem
imageUrl={data.imageUrl}
author={data.author}
title={data.title}
content={data.content}
date={data.date}
key={data.id}
/>
);
})
}
</div>
</div>
</div>
</>
);
};
export default App;
CodePudding user response:
the solution is same as in : How to add active state to div using usestate hook?
try the follow the same pattern in the answer,
I hope i answered ur question.