Create a React App With a .NET Core Backend

React and .NET logos

React has emerged as one of the most popular frontend JavaScript frameworks for building dynamic user interfaces. When it comes to backend technologies to pair with React, .NET Core is a compelling option. As a mature, open-source, cross-platform framework, .NET Core provides a robust foundation for building scalable web APIs and services.

In this in-depth guide, we‘ll walk through the process of creating a React application with a .NET Core backend from start to finish. Whether you‘re new to React or .NET Core, or an experienced developer looking to combine these powerful technologies, this tutorial has you covered. Let‘s dive in!

Why Use React with .NET Core?

Before we get to the code, let‘s consider some of the key benefits of using React with .NET Core:

React Advantages

  • Component-based architecture for building reusable UI elements
  • Virtual DOM for efficient updates and rendering
  • Rich ecosystem of third-party libraries and tools
  • Declarative syntax that‘s easy to read and understand

.NET Core Advantages

  • Cross-platform and open-source
  • High-performance and scalable
  • Extensive class libraries and built-in dependency injection
  • Strong typing and object-oriented programming with C#

Together, React and .NET Core provide a modern, efficient tech stack for full-stack web development. You can take advantage of React‘s declarative UI components on the frontend with .NET Core‘s robustness on the backend.

Setting Up the Development Environment

To get started, you‘ll need to install some prerequisites on your development machine:

Once you have these installed, open Visual Studio and select "Create a new project." Choose the "ASP.NET Core with React.js" project template, give your project a name, and click "Create."

New ASP.NET Core React project dialog

This will set up a starter project with a React frontend and .NET Core backend pre-configured to work together. The project structure should look something like this:

React .NET project structure

The ClientApp folder contains the React frontend code. The Controllers, Models, and Pages folders make up the .NET Core backend.

Building the Backend API with .NET Core

With our project set up, let‘s turn our attention to the backend. We‘ll use .NET Core to build a Web API that our React frontend can call to fetch and modify data.

First, let‘s define a model class to represent the data our API will send and receive. In the Models folder, create a new class called TodoItem:

public class TodoItem
{
  public long Id { get; set; }
  public string Name { get; set; }
  public bool IsComplete { get; set; }
}

Next, create a new controller for our API methods. In the Controllers folder, add a new controller called TodoController:

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
  private readonly TodoContext _context;

  public TodoController(TodoContext context)
  {
    _context = context;
  }

  [HttpGet]
  public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
  {
    return await _context.TodoItems.ToListAsync();
  }

  [HttpPost]
  public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem item)
  {
    _context.TodoItems.Add(item);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(GetTodoItem), new { id = item.Id }, item);
  }

  // Other CRUD methods
}

This controller defines GET and POST methods for retrieving and creating to-do items. The other CRUD methods would follow a similar pattern.

To provide data persistence, we‘ll use Entity Framework Core with SQL Server. First, install the necessary NuGet packages in your project:

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools

Then create a TodoContext class to act as our database context:

public class TodoContext : DbContext
{  
  public TodoContext(DbContextOptions<TodoContext> options)
    : base(options)
  {    
  }

  public DbSet<TodoItem> TodoItems { get; set; }
}

To use this context, update Startup.cs to add it to the service container and configure the connection string:

public void ConfigureServices(IServiceCollection services)
{
  services.AddDbContext<TodoContext>(opt =>
    opt.UseSqlServer("YOUR CONNECTION STRING"));

  // Other services  
}

With that, our backend API is set up to manage to-do items in a SQL Server database. Let‘s switch gears to the frontend.

Building the React Frontend

The React code for our frontend lives in the ClientApp directory. The entry point is index.js, which renders the root App component:

import ‘bootstrap/dist/css/bootstrap.css‘;
import React from ‘react‘;
import ReactDOM from ‘react-dom‘;
import { BrowserRouter } from ‘react-router-dom‘;
import App from ‘./App‘;

const baseUrl = document.getElementsByTagName(‘base‘)[0].getAttribute(‘href‘);
const rootElement = document.getElementById(‘root‘);

ReactDOM.render(
  <BrowserRouter basename={baseUrl}>
    <App />
  </BrowserRouter>,
  rootElement);

The App component sets up the main layout with a nav menu and renders other components based on the current route:

import React, { Component } from ‘react‘;
import { Route } from ‘react-router‘;
import { Layout } from ‘./components/Layout‘;
import { Home } from ‘./components/Home‘;
import { FetchData } from ‘./components/FetchData‘;
import { Counter } from ‘./components/Counter‘;

import ‘./custom.css‘

export default class App extends Component {
  static displayName = App.name;

  render () {
    return (
      <Layout>
        <Route exact path=‘/‘ component={Home} />
        <Route path=‘/counter‘ component={Counter} />
        <Route path=‘/fetch-data‘ component={FetchData} />
      </Layout>
    );
  }
}

To display our to-do list, let‘s create a new component called TodoList:

import React, { useState, useEffect } from ‘react‘;

const TodoList = () => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    populateData();
  }, []);

  const populateData = async () => {
    const response = await fetch(‘api/Todo‘);
    const data = await response.json();
    setItems(data);
    setLoading(false);
  }

  return (
    <div>


      {loading 
        ? <p><em>Loading...</em></p>
        : <table className=‘table table-striped‘>
            <thead>
            <tr>
                <th>Name</th>
                <th>Is Complete?</th>
            </tr>
            </thead>
            <tbody>
            {items.map(item => 
              <tr key={item.id}>
                <td>{item.name}</td>
                <td>{item.isComplete ? ‘Yes‘ : ‘No‘}</td>
              </tr>
            )}
            </tbody>
          </table>
      }
    </div>
  );
}

export default TodoList;

This component fetches the to-do items from the /api/Todo backend endpoint and displays them in a simple table.

Finally, update App.js to import and render the new TodoList component:

import TodoList from ‘./components/TodoList‘;

export default class App extends Component {
  static displayName = App.name;

  render () {    
    return (
      <Layout>
        {/* other routes */}
        <Route path=‘/todo-list‘ component={TodoList} />        
      </Layout>
    );
  }
}  

With that, we have a basic frontend in place for displaying data from our .NET Core backend API. Of course, a real app would have more features like adding, editing, and deleting items, as well as user authentication. But this gives you a foundation to build upon.

Running the App

To run the application, press F5 in Visual Studio. The backend and frontend will start up, and you can view the app in your web browser, likely at https://localhost:5001.

You should see the nav menu rendered by the React components. Clicking the "Fetch data" link should hit the backend API and display the weather forecast data in a table.

Deploying to Production

When it‘s time to deploy your React/.NET Core app to production, you have a few options. You can deploy to traditional virtual machines, or take a more modern approach with containers and orchestration platforms like Kubernetes.

One of the easiest ways to get started is deploying to Azure App Service. Visual Studio has built-in tools for publishing to Azure.

First, right-click the project in Solution Explorer and choose "Publish." Select "Azure" as the publish target and "Azure App Service (Windows)" as the specific target.

Publish to Azure App Service

Follow the prompts to either select an existing App Service instance or create a new one. Then click "Publish" and Visual Studio will build your app, create the necessary Azure resources, and deploy your code.

Your React/.NET Core app is now live on the web!

Conclusion

In this guide, we‘ve seen how to create a web application with a React frontend and a .NET Core backend. We set up the development environment, built a Web API in .NET Core with a SQL Server database, created React components to fetch and display that data, and finally deployed the app to Azure.

Of course, there‘s much more you can do to flesh out the application. Some next steps to consider:

  • Add more CRUD methods to the backend API
  • Implement forms in React for creating and editing items
  • Integrate user authentication with a service like Auth0
  • Write unit tests for your .NET Core and React code
  • Set up a CI/CD pipeline for automated builds and deployments

I hope this tutorial has given you a solid foundation for building React/.NET Core apps. Happy coding!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *