I am building a React app using Bootstrap 5. I have a dynamic Accordion component grabbing tasks from a list:
import React, {useEffect, useState} from "react";
import 'bootstrap/dist/css/bootstrap.min.css'
import FadeIn from "react-fade-in";
import {PageLayout} from "./page-layout";
import TaskDataService from "../services/TaskService";
export const ProfilePage = () => {
const [tasks, setTasks] = useState([]);
const [currentTask, setCurrentTask] = useState(null);
const [currentIndex, setCurrentIndex] = useState(-1);
useEffect(() => {
retrieveTasks();
}, []);
const retrieveTasks = () => {
TaskDataService.getAll()
.then(response => {
setTasks(response.data);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
const refreshList = () => {
retrieveTasks();
setCurrentTask(null);
setCurrentIndex(-1);
};
const setActiveTask = (task, index) => {
setCurrentTask(task);
setCurrentIndex(index);
};
return (
<PageLayout>
<FadeIn>
<div className="list row">
<div className="col-md-6">
<h4>Tasks List</h4>
<div className="accordion" id="accordionTask">
{tasks &&
tasks.map((task, index) => (
<div className="accordion-item">
<h2 className="accordion-header" id="a$index">
<button className="accordion-button" type="button" data-bs-toggle="collapse"
data-bs-target={"a" + {index}}
aria-expanded={(index === currentIndex ? "true" : "false")}
aria-controls={"a" + {index}}
onClick={() => setActiveTask(task, index)}
>
{task.title}
</button>
</h2>
<div id={"a" + {index}} className="accordion-collapse collapse"
aria-labelledby={"a" + {index}} data-bs-parent={"a" + {index}}>
<div className="accordion-body">
<div>
<label>
<strong>Owner:</strong>
</label>{" "}
{task.ownerName}
</div>
<div>
<label>
<strong>Description:</strong>
</label>{" "}
{task.description}
</div>
<div>
<label>
<strong>Status:</strong>
</label>{" "}
{task.completed ? "Completed" : "Pending"}
</div>
<div>
<label>
<strong>Due Date:</strong>
</label>{" "}
{task.startDate.split("T")[0]}
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</FadeIn>
</PageLayout>
);
};
But when I render this, I get an error:
Uncaught DOMException: Failed to execute 'querySelector' on 'Document': 'a[object Object]' is not a valid selector.
I know that a CSS element cannot start with a number, so I tried to get around this using the below syntax:
data-bs-target={"a" + {index}}
But this gets me the error listed above, which suggests that the index number passed into CSS is not coming in as the correct type to be properly read. Any tips on how to deal with this?
Someone had posted the answer, and now their reply has disappeared so I cannot give them credit. But the answer was to simply not use the double brackets.
Wrong: data-bs-target={"a" + {index}}
Right: data-bs-target={"a" + index}
In the top example, it was basically saying "Insert a property with the value Index" rather than just inserting the value of Index itself, which was a breach of syntax.