Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C# enum to React Component

I am using enum in my .Net Core Web API to list types of cuisine in my project such as

public enum CuisineClass
{
    American = 1,
    British = 2,
    Chinese = 3
}

and so on.

At this point when I'm mapping my GetRestaurantDto and calling my endpoint from in my react SPA, I get the int instead of the string.

Is there a way to get the string instead?

like image 619
John Avatar asked Nov 20 '25 07:11

John


2 Answers

You can use JsonStringEnumConverter. In .NET 5 use it this way:

services.AddControllers()
.AddJsonOptions(o =>
{
    o.JsonSerializerOptions.Converters.Add(new JSonStringEnumConverter());
});
like image 187
mojajoja Avatar answered Nov 21 '25 20:11

mojajoja


Why return the full name? If you are using typescript you can setup the enum on your reactjs application too and handle it as such.

export enum CuisineClass
{
    American = 1,
    British = 2,
    Chinese = 3
}

You can then access the strings from TS if you want How to get names of enum entries?

like image 37
Athanasios Kataras Avatar answered Nov 21 '25 19:11

Athanasios Kataras



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!