Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useRef() Invalid hook call

I'm trying to use useRef() hook inside the body of a function component in a NextJs project and I still get the error below. I've gone through the React Hook rules and I can't find the reason for this error and this not working. Does anyone have an idea?

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

import  React, { useRef } from 'react';

export default function Diagram() {

  const svgRef = useRef();

  return (
      <>
        <div className="container-svg py-4">
        <svg  ref={svgRef} viewBox="0 0 300 300">
        <g transform="translate(150, 150)">
          <g>
            <path id="triangle" d="M0, -125 L-150,150 L150, 150 L0, -125 M 0,50 L-150, 150 M150, 150 L0,50  L0,-125" stroke="black" fill="none"/>
          </g>
            {
              posts.map( post => {
                return (
                  <circle key={post.id} className="circle" cx={post.point.x} cy={post.point.y} r="5" />
                )
              })
            }
            <circle className="circle" cx="0" cy="0" r="5" />
          </g>
        </svg>
      </div>
      </>
  )
}
like image 339
Die Duro Avatar asked Oct 27 '25 07:10

Die Duro


2 Answers

I am using next 10.1.3 and react 17.0.1 and I used React.createRef() because useRef() wasn't working. I made an example per the question originally asked. I am adding this because the createRef answer in the comments is incomplete and this makes it easy to understand.

import  React from 'react';

export default function Diagram() {

  const svgRef = React.createRef();

  return (
      <>
        <div className="container-svg py-4">
        <svg  ref={svgRef} viewBox="0 0 300 300">

...
like image 171
Ian Poston Framer Avatar answered Oct 28 '25 22:10

Ian Poston Framer


This probably happens because useRef() and other react hooks are exclusive for Client-Side components. If you do not specify that your component is client-side, the later versions of NextJS assumes that this is a Server Side component by default. Use the directive 'use client' to render this component in the client-side environment.

like image 25
Danilo Peña Avatar answered Oct 28 '25 22:10

Danilo Peña



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!