Hi,
In this post, I will try to explain “How to include React in available .Net Core Web Application” You can access example code end of the post. Let’s get start.
I don’t have any project for this example. Because of this I created empty project for this example. You can pass the project create step. The screenshot is as follows.
I selected project template on second step. Example project will be web application.
My project is ready now. Before start to development, I should include some packages for react. This packages are as follows.
React.AspNet,
JavaScriptEngineSwitcher.ChakraCore
JavaScriptEngineSwitcher.ChakraCore.Native.win-x64 (If you are using Windows x86 or another OS, you should download your version for this OS.)
JavaScriptEngineSwitcher.Extensions.MsDependencyInjection
After downloaded packages, I modified startup.cs file in my project. Firstly, I added new libraries to startup.cs. This libraries as follows.
using Microsoft.Extensions.DependencyInjection
using JavaScriptEngineSwitcher.ChakraCore
using JavaScriptEngineSwitcher.Extensions.MsDependencyInjection
using React.AspNet
My page is as follows.
I added the following code to the end of configureservices method.
I added code in configure method as follow. This code must be before static files. The screenshot is as follows.
I created JSX folder in wwwroot. I will use this folder for my react files. Let’s start.
Firstly, I added new div in my masterpage layout. (_layout.cshtml) My react components will use this div. The screenshot is as follows.
Now, I can write react code. I added a new jsx file in my jsx folder. The screenshot is as follows.
My component details are as follows.
In this step, I called react file from _layout.cshtml. I added codes bottom of in my master page as follow. (_layout.cshtml)
Script links are as follows.
https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js
https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js
I started localhost and It worked!
I shared example codes on github. You can access from this link.
Thanks.