I am having hard times with this one.
I created a modal (SetLevel) so the user can select a level and after that what I want is to just update my initial state which goes by the name of level . So I pass my prop in handleChange in the SetLevel component like this:
const Game = () => {
const [levelOpen,setlevelOpen]=useState(false);
const [level,setlevel]=useState(1);
const changedLevel = (newLevel)=>{
console.log('newLevel',newLevel);
setlevel(newLevel);
}
return (
<div>
<h1 className='title'>Find the icons </h1>
<div className='container'>
<button className='btn' onClick={() => setlevelOpen(true)}>
Select level
</button>
<SetLevel isOpen={levelOpen} handleChange={()=>changedLevel(level)}
onClose={()=>setlevelOpen(false)}/>
</div>
<ItemDrag newLevel={level}/>
</div>
);
};
SetLevel child component looks like this:
const SetLevel = ({isOpen,onClose,handleChange}) => {
if (isOpen === false) return null;
const close = (e) => {
e.preventDefault();
if (onClose) {
onClose();
}
};
const handleClick =(num,e)=>{
console.log(num);
handleChange(num)
close(e)
}
return (
<div className='modal-window'>
<div>
<div onClick={(e) => close(e)} className='modal-close'>
CLOSE
</div>
<h1>Select level!</h1>
<button className="btn" onClick={(e)=>handleClick(3,e)} >LEVEL3</button>
</div>
</div>
);
}
So here is how I do it if a user selects level 3 I pass that number to my handleClick function and this function should take care of that handleChange prop as you can see.
But whenever I do this my level is not updating how come?? The value i am getting back is always 1 , why is that? thanks.
>Solution :
You don’t take the return value of the handleChange in the Game component.
Try it like this:
const Game = () => {
const [levelOpen,setlevelOpen]=useState(false);
const [level,setlevel]=useState(1);
const changedLevel = (newLevel)=>{
console.log('newLevel',newLevel);
setlevel(newLevel);
}
return (
<div>
<h1 className='title'>Find the icons </h1>
<div className='container'>
<button className='btn' onClick={() => setlevelOpen(true)}>
Select level
</button>
<SetLevel isOpen={levelOpen} handleChange={(newLevel)=>changedLevel(newLevel)}
onClose={()=>setlevelOpen(false)}/>
</div>
<ItemDrag newLevel={level}/>
</div>
);
};