How can I check the radio button with a single click? and how to select one by default?

Viewed 59

I am trying to make a simple react app that displays radio input for each 'hero' from a list of heroes and if the user checks, the hero's name will be displayed as the favorite hero. But the problem is on my local machine to check a hero I need to double click that radio input. How can I check a hero with a single click? Code of the app.js file is given below:

import React, { useState } from "react";
import "./App.css";
function App() {
    const [heros, setHeros] = useState([
        "Superman",
        "Batman",
        "Antman",
        "Robocop",
    ]);
    const [selected, setSelected] = useState(null);

    const handleChange = (e) => {
        e.preventDefault();
        setSelected(e.target.value);
        console.log(e.target.checked);
    };


    return (
        <div>
            <h1>Select Your Favorite Hero</h1>
            <form onChange={handleChange}>
                {heros.map((hero, index) => (
                    <div key={index}>
                        <input
                            type="radio"
                            name="hero"
                            id={hero}
                            value={hero}
                            
                        />
                        <label htmlFor="{hero}">{hero}</label>
                        <br />
                    </div>
                ))}
            </form>
            <div>
                <p>Your super hero is: {selected}</p>
            </div>
        </div>
    );
}
export default App;
2 Answers

Remove e.preventDefault() inside handleChange function. Function will be like this one.

const handleChange = (e) => {
    setSelected(e.target.value);
    console.log(e.target.checked);
};

First, select the button with #btn id, output element with the #output id, and all the radio buttons with the name heros

const btn = document.querySelector('#btn');

const output = document.querySelector('#output'); const radioButtons = document.querySelectorAll('input[name="heros"]');

Related