Changing css style of a div at runtime using onClick in React

Viewed 71

I've just started using React, so I used the approach used normally in Javascript.

My approach in Javascript I have 6 forms and by using onClick on a span tag i shift the position of a particular form(shifting left and right by 540px) and display it in the div. All other form are located outside the div and I've set overflow : hidden so they are not visible. I just use document.getElementById.style.left = 540px in Javascript.

How can I do the same in ReactJS ? I've tried the same but it says

TypeError:document.getElementById(...) is null

1 Answers

you need to use the useRef() hook here is an example:

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.style.left = 540px();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>go left on click</button>
    </>
  );
}
Related