Problem:
I have two select components right & left side with different values consider A->right side & B->left side, In a button click function I need to swap a A -> select component to Left and B-> select component to right. How to achieve this in react js.
function SelectComponentA({
<select name="Country" id="Country">
<option value="France">France</option>
<option value="Italy">Italy</option>
)}
export SelectComponentA
function SelectComponentB({
<select name="Segment" id="Segment">
<option value="Segment 1">Segment 1</option>
<option value="Segment 2">Segment 2</option>
</select>
export SelectComponentB
I tried using a UseState
const [dropDownSwap, setSwap] = useState(true)
function swapDropDownComponents() {
setSwap(!dropDownSwap)
}
{dropDownSwap ? SelectComponentA : SelectComponentB}
<button type="button" Onclick={SwapSelectComponent}>Swap</button>
Solution:
If you want to swap the two components on button click then you need to define the structure in the condition rendering. With the help of useState toggle the boolean value to set the specific structure. This is demonstrated by the following code.`
const [swap, setSwap] = useState(false)
const Select1 = () => {
return (
<>
<label for="cars">Select Component A</label>
<select name="Country" id="Country">
<option value="France">France</option>
<option value="Italy">Italy</option>
</select>
</>
)
}
const Select2 = () => {
return (
<>
<label for="cars">Select Component B</label>
<select name="Segment" id="Segment">
<option value="Segment 1">Segment 1</option>
<option value="Segment 2">Segment 2</option>
</select>
</>
)
}
return (
<div>
{swap ? <div> <Select1 /><Select2 /> </div> : <div> <Select2 /><Select1 /> </div>}
<div>
<button onClick={()=>setSwap(!swap)}>Button</button>
</div>
</div>
)`