'I'm working with reactjs and cannot seem to prevent this error when trying to display JSON data (either from file or server):
I want to open one accordion at a time when I open other accordion second one should get closed. I am trying but I don't know where I am going wrong.
const [courses, setCourses] = useState([]);
const [city,setCity]= useState([]);
const [countries, setCountries] = useState([]);
const [filteredCourses, setFilteredCourses] = useState([]);
const [categories, setCategories] = useState([]);
const [filteredcity, setFilteredCity] = useState([]);
const onClickButton = (chosenCategory) => {
setFilteredCourses(courses.filter(course => course.coursecategory === chosenCategory)
)}
useState(() => {
Axios
.get("http://localhost:3100/courses")
.then((response) => {
setCourses(response.data);
setFilteredCourses(response.data);
setCategories(_.uniqBy(response.data.map(course => course.coursecategory)));
})
.catch((error) => {
console.log(error);
});
}, []);
useEffect(()=>{
fetch('http://localhost:3100/allcourses')
.then((res)=>res.json())
.then((results)=>setCourses(results));
},[]);
useState(() => {
Axios
.get("http://localhost:3100/cities")
.then((response) => {
setCity(response.data);
setFilteredCity(response.data);
setCountries(_.uniqBy(response.data.map(city => city.country)));
})
.catch((error) => {
console.log(error);
});
}, []);
This is the accordion code:
{
categories.map((category, index) => (
<>
<Accordion key={index}>
<Card>
<Accordion.Toggle
as={Card.Header}
eventKey='0'
type='button'
onClick={() => onClickButton(category)}
>
<ul id={id.categorylist} onClick={() => onClickButton(category)}>
{' '}
{category}{' '}
<FaChevronDown style={{ marginLeft: '100%' }}></FaChevronDown>{' '}
</ul>
</Accordion.Toggle>
<Accordion.Collapse
eventKey='0'
onClick={() => onClickButton(category)}
>
<Card.Body>
<div>
<div>
{filteredCourses.map((course, index) => (
<a
href={`/course/${course.course_slug}`}
as={Link}
key={index}
>
{' '}
{course.coursename}
</a>
))}
</div>
</div>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</>
));
}
All data are coming dynamically based on the categories I choose but when I open two accordion at a time it display second accordion data which I have opened recently, I want to open one accordion panel at a time when one panel open other should get closed. I tried all solution but not getting proper solution for this when I use my code.
Above link what i am getting output both accordion is open at a time and for both categories its showing same result but i have different courses for different categories i want to show particular course for particular category for which i need to close first accordion panel when second is open
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
