I use a map with custom markers on the site. On the right is a list of houses that match the markers. I need to implement the following: when clicking on a marker, the house that corresponds to the marker goes to 1st place in the list. Marker coordinates and house information comes from Firebase. Now I have implemented the code for this logic, but when I click on the marker, I get an error - Objects are not valid as a React child. How can it be solved?
const List = ({ selectedHouse }) => {
const [houseTitles, setHouseTitle] = useState([]);
useEffect(() => {
const q = query(collection(db, "map-markers"));
onSnapshot(q, (querySnapshot) => {
setHouseTitle(
querySnapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
);
});
}, []);
return (
<div style={{ width: "50%" }}>
{<ListItem title={houseTitles[selectedHouse]} />}
{houseTitles
.filter((title, index) => index !== selectedHouse)
.map((title, index) => (
<ListItem key={index} title={title.data.title} />
))}
</div>
);
};
console.log(houseTitles[selectedHouse]):
CodePudding user response:
You don't need curly brackets when using components like that;
...
...
return (
<div style={{ width: "50%" }}>
{houseTitles[selectedHouse] && houseTitles[selectedHouse].data ? <ListItem title={houseTitles[selectedHouse].data.title} />:null }
{houseTitles
.filter((title, index) => index !== selectedHouse)
.map((title, index) => (
<ListItem key={index} title={title.data.title} />
))}
</div>
);
...
...
Also, you probably try to print title in ListItem
component yet you pass the whole object for the selectedHouse
Additional info; selectedHouse is empty on the first render
CodePudding user response:
Try this:
const List = ({ selectedHouse }) => {
const [houseTitles, setHouseTitle] = useState([]);
useEffect(() => {
const q = query(collection(db, "map-markers"));
onSnapshot(q, (querySnapshot) => {
setHouseTitle(
querySnapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
);
});
}, []);
return (
<div style={{ width: "50%" }}>
<ListItem title={houseTitles[selectedHouse]?.data?.title} />
{houseTitles
?.filter((title, index) => index !== selectedHouse)
?.map((title, index) => (
<ListItem key={index} title={title?.data?.title} />
))}
</div>
);
};