I want to have a main page that displays a list of four accommodations, with the ability to jump to a specific page per accommodation with a click.
I don’t see where the error comes from.
My code produces
Uncaught TypeError with a message of "Cannot read properties of undefined (reading ‘map’)"
APP.js:
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import AccommodationList from './components/AccommodationList';
import AccommodationDetails from './components/AccommodationDetails';
//import accommodationsData from './data/accommodations.json';
import './styles/accommodations.css';
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<AccommodationList/>}/>
<Route path="/accommodation/:id" element={<AccommodationDetails/>}/>
</Routes>
</BrowserRouter>
);
}
ACCOMMODATIONDETAILS.js:
import React from 'react';
import accommodationsData from '../data/accommodations.json';
import '../styles/accommodations.css';
function AccommodationDetails(props) {
const accommodation = accommodationsData.find((a) => a.id === props.match.params.id);
return (
<div>
<h2>{accommodation.title}</h2>
<p>{accommodation.description}</p>
<p>Prix : {accommodation.price}€</p>
<img src={accommodation.imageURL} alt={accommodation.altTxt} />
</div>
);
}
export default AccommodationDetails;
ACCOMMODATIONLIST.js
import React from 'react';
import { Link } from 'react-router-dom';
import allaccommodations from '../data/accommodations.json';
import '../styles/accommodations.css';
export default function AccommodationList(props) {
return (
<div>
<div>
<h1>Chez Nestor</h1>
<AccommodationList allaccommodations={allaccommodations} />
</div>
<div className='container'>
{props.allaccommodations.map(accommodation => (
<div key={accommodation.id}>
<figure>
<img src={accommodation.imageURL} alt={accommodation.altTxt} />
<figcaption>
<h2>{accommodation.title}</h2>
<p>{accommodation.description}</p>
<p>Prix : {accommodation.price}€</p>
<Link to={`/accommodation/${accommodation.id}`}>Voir plus</Link>
</figcaption>
</figure>
</div>
))}
</div>
</div>
);
}
console.log(allaccommodations)
I tried changing names, or the term ‘element’ by ‘component’. Where does this error come from, and how can I fix it?
2
Answers
Make sure
props.allaccommodations
is defined with some value.Then try using
map
on it.Example:
The issue starts in
AccommodationList
where no props are passed to the component, soprops.allaccommodations
is undefined.You also appear to be recursively rendering the
<AccommodationList />
component, which seems incorrect and unnecessary. It can likely be removed.Assuming you want to render the imported
allaccommodations
it won’t be located on theprops
object, it should be mapped directly.Example: