I'm trying to create my project in React. This part of the project consists in a list of item, each one has a button X to delete that item. Every single item, is a component of my react app. When the button is pressed, i set a variable (passed throught the useContext) called setPopup, so a popup appears, asking if you are sure you want to delete the file. The proble is that when I click the file, this error occurs:
TypeError: Cannot read properties of undefined (reading 'setPopup')
This is the code of the component:
import '../styles/styleF.css';
import {PopupContest} from './HomePage';
import { useContext } from 'react';
const SFile = (n) => {
const v = useContext(PopupContest);
let currentImg = c;
return <>
<div className="fileSingle">
<img src={currentImg} alt="img" style={{'height':'50px', 'width':'50px','position':'relative', 'top':'5', 'left':'0'}} />
<h3>{n.name "." n.img}</h3>
<button style={{'height':'50%', 'marginTop':'10px'}} onClick={() => {v.setPopup(6); v.setSelectFile(n.ident "")}}>X</button>
</div>
</>
}
export default SFile;
I would like to knwo why this is happening, and how to fix it correctly. The code that effectively delete the file is in other file and component, and works. I read in some answers that I should check if it is undefined, but to make the check condition, the code breaks anyway. So, I don't know how to manage it. Can someone help? Thank you so much
CodePudding user response:
The PopupContest
context must have a Provider and this Provider must be wrapped in a component that is parent (any level) of SFile
component. Then you can use the consumer of PopupContest
in SFile
component.
Something like this:
import {Provider as PopupContestProvider} from './HomePage';
return (
<PopupContestProvider>
<SFile />
</PopupContestProvider>
);