-5

I want to add a class to my input only when the component is updated, not when it is mounted. So, every time when I will start to write in the input, I want to add the class: demo.

const App = () => {
  function Change(e) {
    setState(e.target.value);
  }

  useEffect(() => {
   document.getElementById('test').classList.add("demo")
  }, []);
  const [state, setState] = useState(0);
  return (
      <div className="main">\sd
        <input id='test' onChange={Change} type="text"/>
        <p>{state}</p>
      </div>
  );
}

export default App;

How to do this using my code?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415

1 Answers1

1

I'd recommend mapping your requirements more directly to the code instead of trying to hack the behavior of useEffect. Additionally, I'd avoid doing DOM manipulations instead of just doing things with React, since there's no guarantee the same DOM element will be preserved across renders:

const App = () => {
  const [state, setState] = useState({ hasEdited: false, value: '' });
  return (
    <div className="main">
      <input 
        id='test' 
        type="text"
        className={state.hasEdited ? 'demo' : ''}
        onChange={e => setState({ ...state, hasEdited: true, value: e.target.value })}
      />
      <p>{state.value}</p>
    </div>
  );
}
Jacob
  • 77,566
  • 24
  • 149
  • 228