Adding ReactJS to an existing Asp.Net Core 2 Application

August 17, 2018

I’ve recently been playing around with writing an Asp.Net Core 2 app from scratch. If you’re interested, you can view my exploits here.

I came across an interesting issue, which was that I wanted to search an in memory set of data, and I wanted the screen to update as I searched. React sounds like the perfect tool for this; and this article describes how to integrate a React view (JSX file) into an MVC view.

(Note that it doesn’t cover implementing the search function - that will be the subject of a later post when and if I work out how to do it.)

Set-up

After you’ve created your Asp.Net Core 2 application, the first step is to install React; which is a NuGet package:



Install-Package React.AspNet -Source nuget.org

There are some code tweaks that are needed; the first is in startup.cs (which basically tells Asp to use React, and how to do so):



services.AddTransient< …
 
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddReact();
 
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version\_2\_1);




app.UseReact(config =>
{
    
});
 
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

You’ll need to slightly change the signature of ConfigureServices, too:



public IServiceProvider ConfigureServices(IServiceCollection services)
{
. . . 
    return services.BuildServiceProvider();
}

The next thing is to make React available to your views; in ViewImports.cshtml:



@using UsefulSites.Web
@using UsefulSites.Web.Models
@using UsefulSites.Web.ViewModels
@using React.AspNet
@addTagHelper \*, Microsoft.AspNetCore.Mvc.TagHelpers

React Code

Next step is to create the ReactJs file:



class SearchBox extends React.Component {
    render() {
        return (
            <div className="search-container">
                <textarea>
                    Search Text
                </textarea>    
            </div>
        );
    }
}
 
ReactDOM.render(
    <SearchBox />,
    document.getElementById('content')
);

Then change the HTML file:

<div class="row">
    <div class="jumbotron">
        <div id="content"></div>
        <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.development.js"></script>
        <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-dom.development.js"></script>
        <script src="@Url.Content("~/js/search.jsx")"></script>
    </div>

As you can see, the React script references the div named “content” specifically.

References

https://reactjs.net/getting-started/aspnetcore.html

https://reactjs.net/getting-started/download.html



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024