'Rendering based on Enum in ReactJS

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?



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mchowdam
Solution 2 bcjohn