Skip to main content

MERN Show

Let's add a function that will select a holiday when a mouse hovers over one in our list

First, let's add a property to state

const [holidays, setHolidays] = useState([]);
const [holiday, setHoliday] = useState(null);

Let's call setHoliday on mouseover. Again because we want to pass an argument, we must wrap this in an anonymous function

<tr key={index} onMouseOver={() => setHoliday(holiday)}></tr>

Let's show our Show component if holiday has a non false-y value, right after our table

<Show holiday={holiday} />

Create and import the Show component

Show.jsx
const Show = ({ holiday }) => {
if (holiday === null) {
return null;
}

const celebrated = holiday.celebrated ? "Yes" : "No";

return (
<div>
<h2>{holiday.name}</h2>
<h3>Celebrated: {celebrated}</h3>
<p>{holiday.description}</p>
<p>Likes: {holiday.likes}</p>
</div>
);
};

export default Show;

Import into App.jsx

App.jsx
import Show from "./components/Show";

COMPLETED CODE:

App.jsx

App.jsx
import { useEffect, useState } from "react";
import NewForm from "./components/NewForm";
import Show from "./components/Show";

function App() {
const [holidays, setHolidays] = useState([]);
const [holiday, setHoliday] = useState(null);

const addHoliday = (holiday) => {
setHolidays([...holidays, holiday]);
};

const deleteHoliday = async (id) => {
const response = await fetch(`/api/holidays/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
setHolidays(holidays.filter((day) => day.id !== id));
}
};

useEffect(() => {
async function fetchHolidays() {
const response = await fetch("/api/holidays");
const jsonData = await response.json();
console.log(jsonData);
}
fetchHolidays();
}, []);

return (
<div className="container">
<h1 className="title">Holidays! Celebrate!</h1>
<NewForm handleAddHoliday={addHoliday} />
<Show holiday={holiday} />
<table>
<tbody>
{holidays.map((holiday) => {
return (
<tr key={holiday.id} onMouseOver={() => setHoliday(holiday)}>
<td> {holiday.name}</td>
<td onClick={() => deleteHoliday(holiday.id)}>X</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}

export default App;