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

React forwardRef uncaught syntaxError

I create react forwardref. but show one error. i use vite, typescript. here my code:

import * as React from 'react'

interface PageProps {
    number: number;
    children: React.ReactNode
}
  
const PageComponent = React.forwardRef<HTMLDivElement, PageProps>((props, ref) => {
    return (
        <div className="page" ref={ref}>
            <div className="page-content">
                <h2 className="page-header">Page header - {props.number}</h2>
                <div className="page-image"></div>
                <div className="page-text">{props.children}</div>
                <div className="page-footer">{props.number + 1}</div>
            </div>
        </div>
    );
});

export default PageComponent;

show this error:

PageComponent.tsx?t=1711471952502:17 Uncaught SyntaxError: Identifier
‘React’ has already been declared (at
PageComponent.tsx?t=1711471952502:17:92)

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 :

The error you’re encountering suggests that there might be a conflict in how you’re importing React. This issue can arise when you have multiple import statements for React in different files.

Here’s how you can modify your code to avoid the conflict:

import { forwardRef, ReactNode } from 'react';

interface PageProps {
    number: number;
    children: ReactNode;
}
  
const PageComponent = forwardRef<HTMLDivElement, PageProps>((props, ref) => {
    return (
        <div className="page" ref={ref}>
            <div className="page-content">
                <h2 className="page-header">Page header - {props.number}</h2>
                <div className="page-image"></div>
                <div className="page-text">{props.children}</div>
                <div className="page-footer">{props.number + 1}</div>
            </div>
        </div>
    );
});

export default PageComponent;

In above suggestion,forwardRef and ReactNode are imported directly from the react package, and React is not imported since it’s not explicitly used within the component. Kindly revert if this resolves the conflict you’re encountering.

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