I want to develop a parent component in which child component will be rendered by default, it has check box, upon clicking on that check box it will render another child component and that first child component should disappear.
CodePudding user response:
set a state with the initial value true a when change the check box set it to false and write condition to state? <First/>: <Second/>
CodePudding user response:
I have created a switch on/off app for you, it would solve your issue:
import React from 'react'
import { useState } from 'react'
const Stack = () => {
const [swith, setSwitch] = useState(true)
const [count, setCount] = useState(0)
const handleCounterIncrease = () => {
if (count < 100) {
setCount(count 5)
}
else {
setCount(100)
}
}
const handleCounterDecrease = () => {
if (count > 5) {
setCount(count - 5)
}
else {
setCount(0)
}
}
const handleSwitchOff = () => {
setSwitch(false)
}
const handleSwitchOn = () => {
setSwitch(true)
}
return (
<div>
{
swith ?
<div>
<p>{count}</p>
<div style={{ display: "flex" }}>
<button onClick={handleCounterIncrease} style={{ backgroundColor: 'green', padding: '3px', marginRight: '20px' }}>Increase </button>
<button onClick={handleCounterDecrease} style={{ backgroundColor: 'red', padding: '3px' }}> Decrease</button>
</div>
</div>
: "Rainbow"
}
<div style={{ display: "flex", marginTop: '20px' }}>
<button onClick={handleSwitchOn} style={{ backgroundColor: 'green', padding: '3px', marginRight: '20px' }}>swith on </button>
<button onClick={handleSwitchOff} style={{ backgroundColor: 'red', padding: '3px' }}>swith off</button>
</div>
</div>
)
}
export default Stack