0

I am working on Reactjs,I have list of questions(using loop) with radio button and i want to add class on radio button which clicked,But right now unable to add class, Here is my current code

<FormControlLabel
                    key={`radio${item.id}${count + 2}`}
                    value={item.id.toString()}
                    control={<Radio color="primary" required={item.required} />}
                    label={getChoice(item)}
                    onClick={myfunct}
                  />
                ))}

And in juqery i am using following code

   const myfunct = event => {
         $(this).addClass('my-selected-item');
     }
1
  • 1
    Mixing jQuery and React is a recipe for a lot of headaches. React already has good ways of dealing with state management and styles, such as this answer. Commented Jan 8, 2023 at 5:51

1 Answer 1

1

it is not good idea to change DOM elements directly like this. Better store the status of class being added to the element in a state

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [active, setActive] = useState(false);

  const handler = () => setActive(!active);
  return (
    <div className={active ? "active" : ""} onClick={handler}>
      hello
    </div>
  );
}

just little css to test the presence of class

.active {
color: red
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.