i'm trying to make a on-off switch in Next.Js. For help i watched this video: https://www.youtube.com/watch?v=1W3mAtAT7os&t=740s The Problem is, everytime i reload the page the switch requires 2 clicks before moving the switch and 3 clicks to turn it back off
here is the code in my .js file
import React, { useEffect, useState } from 'react'
export default function Navigation() {
const [menuActive, setMenuActive] = useState(false);
const Toggle = ({onChange}) =>
<label className='menu-button'>
<input type="checkbox" onChange={onChange} className='input'/>
<span className='slider'/>
</label>
;
return (
<div>
<div className='menu-button-container'>
<Toggle onChange={(event) => setMenuActive(event.target.checked)} />
</div>
</div>
)
}
and here is the CSS:
.menu-button-container {
width: 50%;
height: 125px;
right: 0;
display: flex;
justify-content: flex-end;
align-items: center;
position: fixed;
}
.menu-button {
position: relative;
width: 90px;
display: flex;
justify-content: center;
}
.input {
position: absolute;
left: -9999px;
top: -9999px;
}
.input:checked .slider:before {
width: 17px;
height: 17px;
border-radius: 50px;
transition: 0.3s;
background: white;
background-repeat: no-repeat;
background-size: 12.5px;
background-position: center;
left: 30px;
content: "";
}
.slider {
display: flex;
cursor: pointer;
width: 50px;
height: 25px;
border-radius: 100px;
background-color: black;
position: relative;
align-items: center;
z-index: 2;
}
.slider:before {
content: "";
position: absolute;
left: 2px;
width: 17px;
height: 17px;
border-radius: 50px;
transition: 0.3s;
background: white;
background-repeat: no-repeat;
background-size: 12.5px;
background-position: center;
}
Thanks in advance :)
CodePudding user response:
You forgot to pass the checkbox value in Toogle component !
Try this code it's work !
import React, { useEffect, useState } from 'react'
export default function Navigation() {
const [menuActive, setMenuActive] = useState(false);
const Toggle = ({ onChange, value }) =>
<label className='menu-button'>
<input checked={value} type="checkbox" onChange={onChange} className='input' />
<span className='slider' />
</label>
;
return (
<div>
<div className='menu-button-container'>
<Toggle value={menuActive} onChange={(event) => setMenuActive(event.target.checked)} />
</div>
</div>
)
}
CodePudding user response:
Try with true value instead of false.
import React, { useEffect, useState } from 'react'
export default function Navigation() {
const [menuActive, setMenuActive] = useState(true);
const Toggle = ({onChange}) =>
<label className='menu-button'>
<input type="checkbox" onChange={onChange} className='input'/>
<span className='slider'/>
</label>
;
return (
<div>
<div className='menu-button-container'>
<Toggle onChange={(event) => setMenuActive(event.target.checked)} />
</div>
</div>
)
}
