Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use styling with useRef hook?

I am trying to use useRef to move items of a component at the click of a button. I have tried the following code:

export const List: React.FC = () => {
  const listRef: any = useRef(null);
  const handleSliderClick = (direction: string) => {
    if (direction === "left") {
      console.log(listRef.current, "refff");
      listRef.current.style.transform = `translateX(230px)`;
    }
  };
  return (
    <div className="movie-list">
      <span className="list-title">Continue to watch</span>
      <div className="wrapper">
        <ArrowBackIosOutlined
          className="slider-arrow left"
          onClick={() => handleSliderClick("left")}
        />
      </div>
    </div>
  );
};

I am getting the error, ‘TypeError: Cannot read properties of null (reading ‘style’)’.
What is the correct way to use useRef?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Need to assign the ref to an element that you want to manipulate. eg

  <div className="wrapper" ref={listRef}>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading