I am trying to learn react and creating application First time. I have created basic application where just displaying two link on page with home and view. when click on view it will read data from file (data.json) and try to load data on the page and display . I can see data in console log but dont know why its not displaying on page. Also seems like my application routing isnt perfect. Please help me understand or guide me how I can make it correct.
App.js
function App() {
return (
<Menulink />
);
}
export default App;
View.js
import React, { useState, useEffect } from 'react';
export function View(){
const [data, setData] = useState([]);
useEffect(() => {
fetch("/data.json")
.then((res) => {
console.log(`got response ${res}`);
return res.json();
}).then((data) => {
console.log(`data : ${JSON.stringify(data)}`);
if (Array.isArray(data)) {
setData(data);
} else {
// Do something to transform it to an array
}
});
}, []);
return (
<div>
<h2>Data from JSON:</h2>
<ul>
{
!data ? "No data found" : data.map(d=>(
<div>
<p>Id:{d.id}</p>
<p>Name:{d.name}</p>
<p>description:{d.description}</p>
</div>
)
)
}
</ul>
</div>
);
}
Menulink.js
export function Menulink() {
return (
<BrowserRouter>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/">View</Link></li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/" element={<View />} />
</Routes>
</BrowserRouter>
);
}
Home.js
export function Home() {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to the home page!</p>
</div>
);
}
when i click on view it dont display data. Please help me understand what is wrong in code. i am creating application first time. Thank you
In Menulink.js, both routes were using the same path ("/"), causing React to always render the Home component. The correct approach is to assign a unique path to each route, such as "/view" for the View component. Additionally, the navigation link for "View" was incorrectly pointing to "/" instead of "/view", preventing it from loading the correct component. Updating the link to View resolves this issue, ensuring proper navigation and rendering of components.
export function Menulink() {
return (
<BrowserRouter>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/view">View</Link></li> {/* Fixed the path */}
</ul>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/view" element={<View />} /> {/* Fixed the path */}
</Routes>
</BrowserRouter>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>