Home > Mobile >  How to use styling with useRef hook?
How to use styling with useRef hook?

Time:12-12

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?

CodePudding user response:

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

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

CodePudding user response:

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

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