+ 3

Why do window.onclick function works when state isn't 0?

So i have two click handler functions inside change component that should only work if state is 0 ,but even when state is 1 window.onclick works? Note:if you click on square ,add image box appears whose state is 0 ,and when you click on add Image whatever appears next is having state 1 and when you click outside square window.onclick event triggers https://code.sololearn.com/WM8EyhjQdJBc/?ref=app

4th Aug 2020, 4:49 PM
Abhay
Abhay - avatar
3 ответов
+ 2
window.onclick gets set when state==0 but you never unset it when state==1 so it will still trigger. However more importantly, you shouldn't mix plain HTML/JS with React. All those document.querySelectors really need to go, aswell as setting .onclick handlers on variables. Components should have no contact with the "outside" - everything that is needed should be passed in through properties, apart from the state defined by useState. Here you should write a <Cube> component for drawing the cube, and a <Form> component for handling the inputs, possibly consisting of smaller components. <input>s and other form elements can be tricky in react at first so keep that in mind! Maybe a <Root> component would also be sensible, it could hold your onclick handler, instead of window. (<Root onClick={...}>) Then you just wire these components up correctly by passing the necessary props. Also on a side note, <>...</> is a shorthand for <React.Fragment>...</React.Fragment>.
4th Aug 2020, 10:56 PM
Schindlabua
Schindlabua - avatar
+ 2
Schindlabua thank you very much again! ,and I just started out with React so trying to implement the plain JavaScript using it, which is more intuitive to me as everything is straightforward unlike react or jsx syntax ,a lot to think about but at the same time it's manageable i believe so,and I don't really know if I will turn to react completely ,js will cover most of my code often ,thks for all the additional info as well ,I really appreciate it .
4th Aug 2020, 11:23 PM
Abhay
Abhay - avatar
+ 1
Yep it took me a bit to get used to the react way of writing code, but for larger applications react is unbeatable and plain js gets messy, fast!
5th Aug 2020, 8:43 AM
Schindlabua
Schindlabua - avatar