Home > database >  How to implement client-side on ASP.NET CORE MVC project with RactJS Component
How to implement client-side on ASP.NET CORE MVC project with RactJS Component

Time:01-31

i have an ASP.NET CORE MVC project and i want that my Razor pages implement ReactJS component. I can load the component App but when i tried to use console.log it doens't work. I figure out that is because the component load only on server side but i can't find a correct way to allow my client-side to access to component and use the js to print in the console a value that i want.

First solution i tried was by follow this link: https://reactjs.net/features/server-side-rendering.html

But when it says to add :

@Scripts.Render("~/bundles/main")
@Html.ReactInitJavaScript()

I have 2 problem:

  1. don't foud @Script so i had to install WebOptimize..but now it says that cannot fine the Ihtml string
  2. i don't have this '~/bundles/main', what is that file? i have to install packages?
  3. with ReactInitJavaScript component is showen but in the inspector says that component is undefined and in the class cannot find React.Component

So, the value are showen but i can't access to console. What i have to insert in the code to enable the client-side??

_Layout.cshtml:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - SportData</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    
    <link rel="stylesheet" href="~/css/card.css" asp-append-version="true" />
</head>
<body>
     
    <div >
        <main role="main" >
            @RenderBody()
        </main>
    </div>
  

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    
    @await RenderSectionAsync("Scripts", required: false)
</body>

</html>

Index.cshtml

@using Newtonsoft.Json;
@using SportData.Web.Models;
@using System.Web.Optimization;


@model SportContainer


@Html.React("App",new { Property1 = "value1", Property2 = "value2" })

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
@Scripts.Render("~/bundles/main")
@Html.ReactInitJavaScript()
             

App.jsx:

class App extends React.Component{

    componentDidMount() {
        console.log('hi')
    }
    
    render() {
        console.log(this.props)
        const { Property1, Property2 } = this.props

        const handler = (event) => {
            console.log(event);
        }
        return (
            <div>
                <button onClick={handler}> clicca </button>
                {console.log(this.props)}
                <p>Property1: {Property1}</p>
                <p>Property2: {Property2}</p>
                <div className="box">Sono un box</div>
            </div>

            );
    }
}

Program.cs:

var builder = WebApplication.CreateBuilder(args);
        
        // Add services to the container.
        builder.Services.AddControllersWithViews();

        builder.Services.AddMvc().AddRazorRuntimeCompilation();

        //builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();  
        builder.Services.AddReact();
        builder.Services.AddHttpContextAccessor();
        
        builder.Services.AddJsEngineSwitcher(option => option.DefaultEngineName = V8JsEngine.EngineName).AddV8();
        
        
        var app = builder.Build();
        // configure middleware
        
        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseReact(config => {
            config.AddScript("~/js/App.jsx");
        });
        
        ReactSiteConfiguration.Configuration.JsonSerializerSettings.ContractResolver = new DefaultContractResolver();

        
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

        app.Run();
        

CodePudding user response:

To implement a ReactJS component in an ASP.NET Core MVC project, you need to perform the following steps:

Add the ReactJS library to your project: You can add the ReactJS library to your project by downloading it from the official ReactJS website or using a package manager like npm.

Create a ReactJS component: Create a new JavaScript file and write the ReactJS component. The component should be a class that extends the React.Component class.

Add the ReactJS component to your ASP.NET Core MVC project: You can add the ReactJS component to your ASP.NET Core MVC project by referencing the JavaScript file in your HTML file. You can add the reference to the HTML file in your ASP.NET Core MVC project by adding it to the head section of your HTML file.

Render the ReactJS component in your ASP.NET Core MVC project: To render the ReactJS component in your ASP.NET Core MVC project, you need to use the ReactDOM.render method. You can add the ReactDOM.render method to your JavaScript file.

Here's an example of how to implement a simple ReactJS component in an ASP.NET Core MVC project:

// ReactJS component

class HelloMessage extends React.Component {
  render() {
    return <div>Hello, {this.props.name}</div>;
  }
}

// Add the ReactJS component to your ASP.NET Core MVC project

class HelloMeassage extends React.Component {
  render() {
    return <div>Hello, {this.props.name}</div>;
  }
}

In the HTML file of your ASP.NET Core MVC project, you need to add a div with an id of root where the ReactJS component will be rendered:

<div id="root"></div>

Once you have added the ReactJS component to your ASP.NET Core MVC project, you should be able to see the output of the component in your web browser.

CodePudding user response:

you have to use react js with api this is way.because if you will use react js like this you cannot make rich ui and also issues with the packges but if you want to use like this so you have to use like this. check here

  • Related