'.click() triggering twice and also results in having to click the browser back button twice to return to the previous page
The code below represents two sets of radio buttons. One button in each set must be clicked at all times. Clicking on one button in each set will navigate the user to a new page where they'll have the same radio buttons on that new page.
To achieve this I used a combination of useRef and .current.click() but the issue of doing it this way is that it triggers two clicks every time something on the page changes and that results in having to click the browser back button twice for each time a change is made. This wouldn't be very practical.
I've tried the defaultchecked property for radio buttons and it doesn't work properly for this case (needs to be manually clicked on again even though the visual shows it to be clicked on by default).
I know local Storage is another option but my coding skills are very limited and I'm not sure how to properly integrate it with my current code.
Any help would be greatly appreciated!
import React, { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
export default function DisplayHomeOptions() {
let navigate = useNavigate();
const [formData, setFormData] = useState({ location: "", selector: "" })
const globalRef = useRef(null);
const messagesRef = useRef(null);
useEffect(() => {
globalRef.current.click();
messagesRef.current.click();
}, []);
function handleChange(event) {
const { name, value, type, checked } = event.target
setFormData(prevFormData => {
return { ...prevFormData, [name]: type === "checkbox" ? checked : value }
})
}
useEffect(() => {
const { location, selector } = formData;
if (location && selector) {
const target = navTarget[location][selector];
if (target) { navigate(target); }
}
}, [formData]);
const navTarget = {
National: { Messages: "/national/messages", Polls: "/national/polls", Questions: "/national/questions", },
Global: { Messages: "/global/messages", Polls: "/global/polls", Questions: "/global/questions", }
}
return (
<div>
<fieldset>
<legend>Option #1</legend>
<input type="radio" name="location" value="Global" onChange={handleChange} ref={globalRef} />
<label htmlFor="Global">Global</label>
<input type="radio" name="location" value="National" onChange={handleChange} />
<label htmlFor="National">National</label>
</fieldset>
<fieldset>
<legend>Option #2</legend>
<input type="radio" name="selector" value="Messages" onChange={handleChange} ref={messagesRef} />
<label htmlFor="Messages">Messages</label>
<input type="radio" name="selector" value="Questions" onChange={handleChange} />
<label htmlFor="Questions">Questions</label>
<input type="radio" name="selector" value="Polls" onChange={handleChange} />
<label htmlFor="Polls">Polls</label>
</fieldset>
</div>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
