Ritika
Ritika

Reputation: 151

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?

Upvotes: 0

Views: 171

Answers (2)

Priyen Mehta
Priyen Mehta

Reputation: 1187

You need to assign your ref to element, then it will work.

    <div className="wrapper" ref={listRef}>

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41397

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

  <div className="wrapper" ref={listRef}>

Upvotes: 1

Related Questions