Home > Enterprise >  Rendering based on Enum in ReactJS
Rendering based on Enum in ReactJS

Time:05-14

In App.js

import "./styles.css";
import { IconType }, Icon from "./icons"; //<-this line gives syntax error

export default function App() {
    return <Icon icon=IconType.Complete/>
};

In icon.js

import React, { useMemo } from 'react';

export enum IconType //<-this line gives syntax error
{
     Complete,
     Active,
     Risk,
     Overdue
}
const Icon = ({ props }) => {
     if (props.icon === IconType.Complete){
       return <h1>icon</h1>
     }
}

export default Icon;

See codesanbox

How should I fixed the syntax error above marked in the comment?

CodePudding user response:

You are getting an error and you can observe from the description 'enum' declarations can only be used in TypeScript files.

From the documentation.

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript.

Read this for better understanding.

CodePudding user response:

Enum is a feature used in typescript and it can not be used in .js files.

So, the first way is to install typescript and rename the .js to .tsx. The file extension of .tsx let you can write typescript and jsx. For more explanation please reference this.

I have been improved on this changes and this is a workable example codesanbox.

  • Related