I got an error for using React.useRef inside a react function component
Asked Answered
S

2

6

I am using React.useRef inside a react functional component, I am getting an error message before i was using it inside a class component and now i have changed it to a react functional component and I am still getting this error message below.

React Hook "React.useRef" is called in function "landingPage" which is neither a React function component or a custom React Hook function

Could you please explain why am i still getting this message after placing in a functional component. Here is my code

import React from "react";
import Modal from "./Modal";

function landingPage() {
  const modalRef = React.useRef();

  return (
    <div className="landingPage">
      <div className="container">
        <div className="landingPage__row">
          <div className="playvideo-wrapper">
            <div className="playvideo-text">See us in action</div>
            <div className="playvideo-button" onClick={openModal}>
              <p>Play Video</p>
            </div>
            <Modal ref={modalRef}>
              <iframe
                src="https://www.youtube.com/embed/SQ8CvT25_Dg?autoplay=1"
                frameborder="0"
                allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
                allowfullscreen
              ></iframe>
            </Modal>
          </div>
        </div>
      </div>
    </div>
  );
}

export default landingPage;

and here is my code in app.js

import React, { Component } from "react";
import LandingPage from "./LandingPage";

export default class App extends Component {
  render() {
    return (
      <div className="main">
        <LandingPage />
      </div>
    );
  }
}

Symbolist answered 1/3, 2020 at 21:57 Comment(1)
I think you need to use forwardRef here on your Modal component. reactjs.org/docs/forwarding-refs.htmlOctagon
S
25

React components MUST start with a capital letter. Change this:

function landingPage() {...

to this:

function LandingPage() {...
Stewardess answered 1/3, 2020 at 22:19 Comment(2)
Otherwise React thinks it's just a regular Javascript function, and hooks aren't allowed in thoseStewardess
@CodeNinja no worries. If this resolves everything for you please mark it as the correct answer :)Stewardess
E
1

I had the same problem, always remember that every React component MUST start with a Capital letter,

Rename your

function landingPage(){...} to function LandingPage(){...}.

The Reason behind this is that state changes are done in classes, and so these will refer your functions as Classes, and for classes, the first letter of the class should be in Capital Letter.

Epsom answered 2/1, 2023 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.