Integrate React components into an existing NET Core app

Viewed 873

I have an existing application build with .Net Core Framework. I would like to integrate React components for re-usability purposes which at this point will only be app specific. I have gone through numerous "Hello World!!" tutorials but that doesn't satisfy my need. I have also looked at reactjs.net but that also is not going to help me as the components gets rendered on the View

Scenario

Application has lots of Modals with a form which gets rendered on numerous pages. Currently it is being handled with JavaScript. The JavaScript code gets duplicated a lot to achieve it.

Goal

Would like to have a react component to replace above mentioned functionality to reduce code getting duplicated.

The problem I am facing is I am not sure how will I be able to interact with the component from a jQuery/JavaScript point of view.

Example

I have a DataTable and one of the actions is to click on a certain button to display the Modal. The code is in a separate .js file so it is separate from the View. So in this case if I click on a button I would like to render the react component. I would need to pass props through to the components and that is where I am uncertain how would I handle it :-(

Any suggestion or guidance would be appreciated.

Thanks in advance

1 Answers

Using react in Asp.Net Core application is easy. At first you need to know your back-end will be API based to communicate with react. So if you have not set up your Core application to an API based, it won't work. Also make sure you have installed nodeJs and other dependencies.

To get started with react, create a new folder in your Asp.Net project solution.

Open the folder in your Command line and execute:

npx create-react-app [your--folder--name]

To view your created app, run

npm start

To get started with asp.net, you need to add spa dependencies in your project.

Then you have to set up your ConfigureService method to include:

services.AddSpaStaticFiles(configuration  => { configuration.RootPath  =  "[your--folder--name]/build"; });

Finally set up your Configure method to include:

app.UseSpaStaticFiles();    
app.UseRouting();    
app.UseEndpoints( ... );    
app.UseSpa(spa => {        
    spa.Options.SourcePath = "[your--folder--name]";        
    if (env.IsDevelopment()) {            
        spa.UseReactDevelopmentServer(npmScript: "start");
    }    
});
Related