2

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
  • The issue is this: so I used the approach used normally in Javascript but that's not how react works. You don't do direct DOM manipulation. You make left part of your component's state instead. Commented Apr 28, 2021 at 10:01

1 Answer 1

1

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>
    </>
  );
}
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.