I wanted to show the button once you hover on the specific color. However, what happens is, hovering on one color will also show the button for other colors of the same products. Also, the button is on the left side part, so if I'll hover to go to the left side, the button won't appear anymore. This is what happens:
How can I fix this?
This is also in codesandbox as well: https://codesandbox.io/s/efqrhd?file=/src/App.js
<Stack
direction={{ xs: "column", sm: "row" }}
spacing={{ xs: 1, sm: 2, md: 4 }}
>
//some codes here
{searchList.map((item, index) => (
<List key={item.id item.color}>
<Paper>
<ListItemText
primary={item.prodName}
secondary={
item.size "(Size)" " - " item.cat "(Category)"
}
/>
{Object.entries(item.colorMap).map((color, i) => (
<div key={i}>
{color[1] !== 0 ? (
<>
<Stack direction="row" spacing={2}>
<Grid
item
xs
key={i}
onm ouseEnter={(e) => showButton(e)}
onm ouseLeave={(e) => hideButton(e)}
>
{color[0]}
</Grid>
{display === true && (
<>
<Grid item xs className={display}>
<Button
onClick={(e) =>
handleAdd(
item.id,
item.prodName,
item.price,
item.size,
item.cat,
color[0]
)
}
>
Add
</Button>
</Grid>
</>
)}
</Stack>
) : (
<>2</>
)}
<br />
</div>
))}
</Paper>
</List>
))}
</Grid>
</Stack>
CodePudding user response:
You can use the :hover css selector if you want something simple.
Add a class to your element in you js file
<div className="color-choice" key={i}>
Use the :hover selector in the css file
.color-choice:hover button { display: block; }
.color-choice button { display: none; }
CodePudding user response:
You will need to play with elements indexes.
instead of display, we will need to get the indexes of the hovered element:
const [displayIndex, setDisplayIndex] = useState({
typeIndex: -1,
colorIndex: -1
});
and the event functions might look like :
const showButton = (typeIndex, colorIndex) => {
// e.preventDefault();
setDisplayIndex({
typeIndex,
colorIndex
});
};
const hideButton = () => {
// e.preventDefault();
setDisplayIndex({
typeIndex: -1,
colorIndex: -1
});
};
and the will to return the button element checking the displayIndex
{
displayIndex.typeIndex === index
&&
displayIndex.colorIndex === i
&&
(<Button ....>Add</Button>
}
Made this modification on your sandbox link https://codesandbox.io/s/add-to-cart-sampled-2-forked-9oi1kn?file=/src/App.js , you might need to fix some styling there.
Hope you find this useful .